特定
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?
})
为什么在.then()链接到doStuff()调用时数据未定义?
解决方法:
因为链接到Promise构造函数的.then()没有返回Promise或其他值.
请注意,.then()返回一个新的Promise对象.
解决方案是返回一个值或其他函数调用,它从.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");
}
// `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`
});