给定
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()电话吗?
data
undefined
.then()
doStuff()
因为没有ed Promise或其他值return从.then()链接到Promise构造函数。
Promise
return
请注意,.then()将返回一个新Promise对象。
解决方案是return使用returnvalue或Promisefrom 的值或其他函数调用.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` });