蓝鸟承诺 – 然后终于
我在Bluebird / Promises中遇到了一些问题。 对于Promise1,一切正常,如果调用fullfill或拒绝。 但是,当我们在finally块中返回Promise2时,它只能用于拒绝,而对于fullfil,我们在callback中得到undefined。
function getPromise1() { return new Promise(function(fulfill, reject) { fulfill("OK1"); }); } function getPromise2() { return new Promise(function(fulfill, reject) { fulfill("OK2"); }); } getPromise1() .then(function(c){ console.log(c); }) .catch(function(e) { console.log(e); }) .finally(function() { return getPromise2(); }) .then(function(c){ console.log(c); }) .catch(function(e) { console.log(e); });
输出:
OK1
未定义
finally
块不会改变返回值。
.finally()有特殊的语义,因为最后的值不能从处理程序中修改。
蓝鸟将等待它,但它不会改变返回值(这是一个自以为是的select,并符合提议的ECMAScript标准语义 – finally
在某些语言和不同于其他语言)。
如果要链接处理程序而不考虑前一个承诺的结果,则可以使用.reflect()将结果转换为PromiseInspection 。
官方的文档就在这里 ,虽然在写这篇文章的时候并没有把这个用例变得非常清楚。
更好的例子:
Promise.resolve("OK1") .then(function(x) { console.log(x); // outputs OK1 return Promise.reject("Rejection demo"); }) .reflect() .then(function(settled) { if (settled.isRejected()) { // outputs Rejected: Rejection demo console.log("Rejected:", settled.reason()); } if (settled.isFulfilled()) { console.log("Fulfilled:", settled.value()); // skipped } return Promise.resolve("OK2"); }) .then(function(c){ console.log(c); // outputs OK2 });