动态序列的承诺(Q)永远不会去捕捉

Dynamic sequence of promise (Q) never go to catch

本文关键字:永远 承诺 动态      更新时间:2023-09-26

我有一些承诺(使用Q),我想顺序调用,这是我的代码:

// All the promises are called sequentially
            var result = promises.reduce(function(promise, item) {
                return promise.then(function () {
                    var obj = toPush.shift();
                });
            }, Q());
            // Check the result
            result.then(function() {
                // Do something if all of the promises full
            }).catch(function() {
                // Do something if ONE of the promise is rejected and stop the others
            }).finally(function() {
                App.network.stopLoader();
            });

promises是一个promise(回调函数)数组

它工作得很好,所有的承诺都是顺序完成的,但是当一个承诺被拒绝时,它仍然进入then函数而不是catch。为什么?

我曾经用过:用Q

打破一个动态承诺序列

谢谢你的帮助

不调用catch的原因是在这部分代码中没有返回任何内容:

return promise.then(function () {
    var obj = toPush.shift();
});

你应该试试:

return promise.then(function () {
    return toPush.shift();
});

如果你这样做:

result.then(console.log)

你应该总是看到undefined,它不会被捕获。

希望这对你有帮助!

看起来你只是想要Q.all:

Q.all(promises).then(function() {
  // Do something if all of the promises full
}).catch(function() {
  // Do something if ONE of the promise is rejected and stop the others
}).finally(function() {
  App.network.stopLoader();
});

根据文档,一旦数组中的任何promise被拒绝,all返回的promise将被拒绝。(与allsettle相反,后者在解析返回的承诺之前等待所有承诺都解决)。