为什么在.then()链接到Promise时未定义值?特定function doStuff(n /* `n` is expected to be a positive number */) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve(n * 10)
}, Math.floor(Math.random() * 1000))
})
.then(function(result) {
if (result > 100) {
console.log(result + " is greater than 100")
} else {
console.log(result + " is not greater than 100");
}
})}doStuff(9).then(function(data) {
console.log(data) // `undefined`, why?})为什么要被拴data undefined在一起打电话?.then()doStuff()
3 回答
白衣染霜花
TA贡献1796条经验 获得超10个赞
因为从链接到构造函数没有Promise或其他值。return.then()Promise
请注意,.then()返回一个新Promise对象。
解决方案是对值或来自return的值或其他函数调用。returnPromise.then()
function doStuff(n /* `n` is expected to be a positive number */) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve(n * 10)
}, Math.floor(Math.random() * 1000))
})
.then(function(result) {
if (result > 100) {
console.log(result + " is greater than 100")
} else {
console.log(result + " is not greater than 100");
}
// `return` `result` or other value here
// to avoid `undefined` at chained `.then()`
return result })}doStuff(9).then(function(data) {
console.log("data is: " + data) // `data` is not `undefined`});
慕尼黑8549860
TA贡献1818条经验 获得超11个赞
doStuff正在返回Promise。但是,你的最后一个then函数没有返回任何值,因此data就是这样undefined。
在promises中,下一个then函数的参数值是前一个函数的返回值then。
function doStuff(n /* `n` is expected to be a positive number */) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve(n * 10)
}, Math.floor(Math.random() * 1000))
})
.then(function(result) {
if (result > 100) {
console.log(result + " is greater than 100")
} else {
console.log(result + " is not greater than 100");
}
return result;
})}doStuff(9).then(function(data) {
console.log(data) // `90`})添加回答
举报
0/150
提交
取消
