当承诺链解决时执行功能

Executing function when chain of promises resolves

我使用 Q.reduce 机制编写了代码,其中函数 insertItemIntoDatabase(item) returns 解决了承诺。

items.reduce(function(soFar,item)
        {
            return soFar.then(function() 
            {
                return insertItemIntoDatabase(item);
            });
        },Q());

是否可以等到链完成后再执行另一个函数,或者我应该以其他方式链接这些函数。

提前感谢您的帮助

这个模式的目的正是:return 对序列结果的承诺。写出来(不带reduce),正好等同于表达式

Q()
.then(function() { return insertItemIntoDatabase(items[0]); })
.then(function() { return insertItemIntoDatabase(items[1]); })
.then(function() { return insertItemIntoDatabase(items[2]); })
…

您可以简单地在其上添加另一个 .then(),它将在链的末尾调用您的回调。

.reduce() 将 return 来自 .reduce() 循环的最终值,在您的情况下这是最终的承诺。要在 .reduce() 链及其所有异步操作完成后执行某些操作,您只需在 returned:

的最终承诺上放置一个 .then() 处理程序
items.reduce(function(soFar,item) {
    return soFar.then(function() {
        return insertItemIntoDatabase(item);
    });
},Q()).then(someOtherFunction);