【问题标题】:Promises .then() with one argument用一个参数承诺 .then()
【发布时间】:2015-01-14 20:57:48
【问题描述】:

我无法理解 Promises/A+ 规范的含义...

https://promisesaplus.com/#point-23

如果你有一个 promise 并调用 .then 并带有一个参数,这是否意味着无论成功或失败都会调用单个参数?

我觉得它可以通过任何方式来解释这一点。我想我最关心的图书馆是Q。

【问题讨论】:

    标签: javascript asynchronous promise q


    【解决方案1】:

    .then() 处理程序的第一个参数,无论它是否是唯一的参数,始终是已完成的处理程序,并且仅在履行承诺时才被调用。如果传递了或没有传递第二个参数,则不会对第一个参数进行不同的处理。

    【讨论】:

      【解决方案2】:

      所以对于任何不确定的人,我制作了一个测试脚本,你可以在你的节点 REPL 中运行它。确定的答案是不,它不会用错误的附件调用成功。

      var Q = require('q');
      
      //call with whether or not the promise will resolve
      function aPromise (bool) {
          var def = Q.defer();
          if (!bool) {
              def.reject("oooo0o0o00o0 rejected");
          }
          def.resolve('winner winner chicken dinner');
          return def.promise
      }
      
      var whatGonnaBe = aPromise(false)
      
      //The Example
      whatGonnaBe
      .then(function (response) {
          console.log('1')
          console.log(JSON.stringify(response) + '1');
      })
      .then(function (response) {
          console.log('2')
          console.log(JSON.stringify(response) + '2');
      },
      function (response) {
          console.log('3')
          console.log(JSON.stringify(response) + '3');
      })
      

      【讨论】:

        【解决方案3】:

        不,第一个参数始终是“成功”或“已解决”的参数。第二个参数始终是失败参数,在将 Promise 链接在一起时可以省略它,并使用单个“失败”参数来处理所有失败。这段代码只是概念性的:

        promise1.then(function() {
            return promise2;
        }).then(function() {
            return promise3;
        }).then(function() {
            /* everything succeeded, move forward */
        }, function() {
            /* catch any failure by any of the promises */
        });
        

        【讨论】:

        • 为什么要返回promise 2
        • 这是我们正在讨论的异步代码。您可以将某些内容推送到 server1,然后更新数据库,然后将某些内容写入文件,最后继续使用您的应用程序。如果这些异步操作中的任何一个失败,您只需编写一个失败处理程序。 编辑: 这也是 Promise 的一个简洁功能,如果你返回一个新的 Promise,它就会成为“新”Promise(因为没有更好的方式来描述它)。
        • 是的,我相当精通 promises,只是有人问我一个关于它们的问题,我觉得我已经使用过一个库,如果你在一个库中省略了失败案例的处理程序然后,它将调用第一个参数,并在响应中附加一个错误,但是当我阅读 A+ 规范时,我解释它应该以另一种方式表现。基本上我希望从这里得到一个明确的答案,而不必编写测试脚本
        猜你喜欢
        • 1970-01-01
        • 2019-02-20
        • 2019-07-09
        • 1970-01-01
        • 1970-01-01
        • 2021-10-17
        • 2018-03-10
        • 1970-01-01
        • 2016-01-21
        相关资源
        最近更新 更多