javascript - Node JS 异步 Promise.All 问题
我正在尝试对从数据库获取的一列表中的多个项目执行异步例程,但我不太理解 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);
});
});
}
目前,我在日志中得到的唯一内容是
~~~ 现在正在通过亚马逊 API 更新所有商品价格 ~~~
我试着在被调用的例程中添加一个日志记录部分,这些例程都成功运行并记录了它们应该记录的内容,但 promise.all.then 没有执行。
我尝试过只是做:
Promise.all(bleh).then(console.log("我们成功了"));
那有效,但当我在 Then 中放入一个函数时,什么都不运行。
请帮忙!
答案#1
Promise.all() 本身非常简单。你传入一个包含多个 promise 的数组。它会返回一个新的 promise,当数组中的所有 promise 都解决时,该 promise 会解决;当数组中的任何单个 promise 拒绝时,该 promise 会拒绝。
var pAll = Promise.all([p1, p2, p3]);
pAll.then(function(r) {
// all promises resolved
// r is an array of results
}, function(err) {
// one or more promises rejected
// err is the reason for the first promise that rejected
});
在你的代码中,Promise.all() 可能不工作的某些原因:
- 你没有向它传递一个包含 Promise 的数组。
- 你传入的数组中的一些 promise 从未解决或拒绝,因此
Promise.all()永远不会解决或拒绝其主 promise - 你没有正确地将回调传递给
.then()处理函数,而实际上你应该这样做 - 你没有正确地从内部函数返回 promise,因此它们无法向外传播或正确链式调用
你的例子:
Promise.all(bleh).then(console.log("We did it"));
错误。你必须像这样将函数引用传递给 .then():
Promise.all(bleh).then(function() {
console.log("We did it")
});
在你的情况下,console.log() 会立即执行,而不会等待 promises 被解决。
在你的详细代码中,你是否百分之百确定:
listing_helper.listingPriceUpdateRoutine(listing.asin)
正在返回一个 promise?而且,这个 promise 会被正确地解决或拒绝吗?
给读者的说明 - 如果你阅读了所有评论,你会看到OP(原作者)真正的问题并不是Promise.all(),而是他们因为向目标主机发送请求过快而被速率限制。由于这个问题本应返回一个请求错误,这个错误应该很容易被看到,显然OP在错误处理或传播上也存在问题,而这个问题可能出现在这里未披露的代码中。
