【发布时间】:2016-04-30 17:10:28
【问题描述】:
我正在尝试对从数据库获取的列表中的一堆项目执行异步例程,但我无法理解 promise.all 的工作原理及其作用。
这是我现在使用的代码:
/**
* Queues up price updates
*/
function updatePrices() {
console.log("~~~ Now updating all listing prices from Amazon API ~~~");
//Grabs the listings from the database, this part works fine
fetchListings().then(function(listings) {
//Creates an array of promises from my listing helper class
Promise.all(listings.map(function(listing){
//The promise that resolves to a response from the routine
return(listing_helper.listingPriceUpdateRoutine(listing.asin));
})).then(function(results){
//We want to log the result of all the routine responses
results.map(function(result){
console.log(result);
});
//Let us know everything finished
console.log("~~~ Listings updated ~~~");
}).catch(function(err){
console.log("Catch: ", err);
});
});
}
现在,我在日志中得到的唯一信息是
~~~ 现在从 Amazon API 更新所有列表价格~~~
我尝试在被调用的例程中添加一个日志记录片段,这些例程都成功运行并记录了它们应该记录的内容,但是 promise.all.then 没有执行。
我已经尝试过:
Promise.all(bleh).then(console.log("我们做到了"));
这行得通,但是当我在 Then 中放置一个函数时,没有任何运行。
请帮忙!
【问题讨论】:
-
tl;博士; - 你在链中的承诺之前错过了回报。
-
好的,快速查看一下代码 - 您缺少两个
returns。一个在你的Promise.all之前和一个在fetchListings()之前,承诺按返回值工作——如果你不从then处理程序返回,它不会等待任何东西。 -
另外,您调用的所有函数都是返回承诺的函数吗?您需要进一步隔离您的问题。
-
您是否控制台记录了所有 isting_helper.listingPriceUpdateRoutine(listing.asin)?真的全部完成了吗(count === listens.length?)
-
@BenjaminGruenbaum 你的建议似乎并没有改变我的结果。 updatePrices 不需要返回任何东西,它只需要记录信息。我尝试将 return 放在 Promise.all 前面和 fetchListings().then 前面,但它什么也没改变。
标签: javascript node.js asynchronous