当时面临的问题:
return
(new Promise(..)) //the promise we want to return
.then(()=>undefined) // the promise were actually returning, which resolves to undefined
您可能已经注意到,然后返回一个新的Promise。这有一个很好的理由,它使Promise链接变得容易,例如:
getUser()//an asynchronous action
.then(user=>login(user))//then if we get the user,promise to log in
.then(token=>console.log("logged in,token is "+token) //then if we logged in, log it
.catch(error=>"login failed");//catch all errors from above
但这也造成了我们面临的小陷阱。解决方案可能是返回原始Promise,而不是.then()自动返回的新Promise,因为它被解析为 undefined 因为 then 内部的函数没有明确返回某些东西:
//what were doing:
Promise.resolve(n*10)//the original promise resolves to n*10
.then(a=>undefined)//the then gets n*10 passed as a, but returns undefined
.then(b=>console.log(b));//b will be undefined :0
//what we want:
var promise=Promise.resolve(n*10);
promise.then(a=>undefined);//a is n*10, this resolves to undefined
promise.then(b=>console.log(b));//but this still logs n*10, as its the original promise :)
因此,如您所见,要返回原始Promise,我们只需将其存储在一个变量中,然后为其分配一个 .then 处理程序,并且仍然具有对原始Promise的引用,我们可以将其他处理程序分配给 ( 或 return )。
在行动:
function doStuff(n /* `n` is expected to be a number */) {
//create a new promise and store it
var promise=new Promise(function(resolve, reject) {
setTimeout(function() {
resolve(n * 10)
},1000);
});
//add a then handler to this promise
promise.then(result=>console.log(result + " is "+result<100?"not":""+" greater than 100"));
//return the original one
return promise;
}
doStuff(9).then(function(data) {
console.log(data) //not undefined, as original promise
})