我使用Q.reduce机制编写代码,其中函数insertItemIntoDatabase(item)返回已解析的promises。
items.reduce(function(soFar,item)
{
return soFar.then(function()
{
return insertItemIntoDatabase(item);
});
},Q());
是否有可能等到链完成然后执行另一个函数或者我应该以其他方式链接这些函数。
提前感谢您的帮助
答案 0 :(得分:1)
此模式的目的正是:返回序列结果的承诺。写出(没有reduce
),它完全等同于表达式
Q()
.then(function() { return insertItemIntoDatabase(items[0]); })
.then(function() { return insertItemIntoDatabase(items[1]); })
.then(function() { return insertItemIntoDatabase(items[2]); })
…
您可以在其上添加另一个.then()
,以便在链的末尾调用您的回调。
答案 1 :(得分:1)
.reduce()
将返回.reduce()
循环中的最终值,在您的情况下,这是最终的承诺。要在.reduce()
链之后执行某些操作并完成所有异步操作,您只需在返回的最终承诺上放置一个.then()
处理程序:
items.reduce(function(soFar,item) {
return soFar.then(function() {
return insertItemIntoDatabase(item);
});
},Q()).then(someOtherFunction);