蓝鸟承诺 - 然后终于

时间:2015-06-29 09:14:12

标签: javascript node.js promise bluebird

我在Bluebird / Promises中遇到了一些问题。 对于Promise1,如果调用fullfill或reject,一切正常。但是当我们在finally块中返回Promise2时,它只适用于reject和fullfil,我们在后面的回调中得到了未定义。

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

未定义

2 个答案:

答案 0 :(得分:7)

finally块不会更改返回值。

  

.finally()有一些特殊的语义,因为无法从处理程序修改最终值。

Bluebird将等待它,但它不会改变返回值(这是一个自以为是的选择并与提议的ECMAScript标准语义一致 - 在某些语言中与finally不同,而不像其他语言。)

答案 1 :(得分:0)

如果您想链接处理程序而不考虑先前的promise的结果,可以使用.reflect()将结果转换为PromiseInspection

官方文档是here,虽然在撰写本文时它并没有真正使用这个用例。

更好的例子:

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
    });
相关问题