【问题标题】:Bluebird promise - then after finally蓝鸟承诺——然后终于
【发布时间】:2015-09-15 16:37:12
【问题描述】:

我在 Bluebird/Promises 中遇到了一些问题。 对于 Promise1,如果调用 fullfill 或拒绝,一切正常。但是,当我们在 finally 块中返回 Promise2 时,它仅适用于拒绝,而对于 fullfil,我们在 then 的回调中得到 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

未定义

【问题讨论】:

    标签: javascript node.js promise bluebird


    【解决方案1】:

    finally 块不会更改返回值。

    .finally() 有特殊的语义,最终值不能从处理程序中修改。

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

    【讨论】:

      【解决方案2】:

      如果您想链接处理程序而不考虑先前的承诺结果,您可以使用 .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
          });
      

      【讨论】:

        猜你喜欢
        • 2014-02-13
        • 1970-01-01
        • 2016-03-20
        • 1970-01-01
        • 1970-01-01
        • 2014-11-06
        • 2015-09-06
        • 2015-02-13
        • 1970-01-01
        相关资源
        最近更新 更多