【问题标题】:Bluebird - how to break promise chain earlyBluebird - 如何提前打破承诺链
【发布时间】:2016-09-03 19:31:14
【问题描述】:
PromiseA().then(function(dataA){
    if (dataA.foo == "skip me")
        return ?? //break promise early - don't perform next then()
    else
        return PromiseB()
}).then(function(dataB){
    console.log(dataB)
}).catch(function (e) {
    //Optimal solution will not cause this method to be invoked
})

如何修改上述代码以提前中断(跳过第二个 then())?

【问题讨论】:

标签: node.js promise bluebird


【解决方案1】:

Bluebird 允许cancel a promise:

var Promise = require('bluebird');
Promise.config({
    // Enable cancellation
    cancellation: true,
});

// store the promise
var p = PromiseA().then(function(dataA){
    if (dataA.foo == "skip me")
        p.cancel(); // cancel it when needed
    else
        return PromiseB();
}).then(function(dataB){
    console.log(dataB);
}).catch(function (e) {
    //Optimal solution will not cause this method to be invoked
});

【讨论】:

  • 在调用之前不需要定义 p 吗?当 p 在这里第一次被调用时,它看起来还没有被定义。
  • @Jonah 我们在异步环境中,函数没有立即执行(它在下一个tick),到它的时候,p 被定义了。
  • p 不是设置为链中最后一条语句的值 - 在这种情况下是 catch?但是,直到调用p.cancel() 之后才会执行捕获
  • Promise 方法将始终同步返回相同的 Promise 以保证您可以继续与更多方法链接。所以链调用的价值总是相同的承诺。示例 const p = Promise.then(...).then(); 返回一个承诺。然后你可以这样做:p.then(...).catch(...);
猜你喜欢
  • 2017-08-06
  • 2017-11-23
  • 2020-02-23
  • 1970-01-01
  • 2015-06-12
  • 2015-08-21
相关资源
最近更新 更多