gpt4 book ai didi

node.js - 当 promise 链解决时执行函数

转载 作者:太空宇宙 更新时间:2023-11-03 23:33:34 25 4
gpt4 key购买 nike

我已经使用 Q.reduce 机制编写了代码,其中函数 insertItemIntoDatabase(item) 返回已解决的 promise 。

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

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

感谢您提前提供帮助

最佳答案

.reduce() 将从 .reduce() 循环中返回最终值,在您的情况下这是一个最终的 promise 。要在 .reduce() 链及其所有异步操作完成后执行某些操作,只需在返回的最终 Promise 上放置一个 .then() 处理程序即可:

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

关于node.js - 当 promise 链解决时执行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35321246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com