我正在尝试对从数据库中获得的列表中的一堆项目执行异步例程,但是我在理解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(“ We done it”)));
并且有效,但是当我将函数放入Then中时,没有任何运行。
请帮忙!
Promise.all()
本身很简单。您通过了一系列的承诺。它返回一个新的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.all()
从不解析/拒绝其主诺言.then()
您应在的处理程序你的例子:
Promise.all(bleh).then(console.log("We did it"));
是错的。您必须.then()
像这样传递函数引用:
Promise.all(bleh).then(function() {
console.log("We did it")
});
在您的情况下,console.log()
可以立即执行,而不必等待承诺被解决。
在您的详细代码中,您100%确保:
listing_helper.listingPriceUpdateRoutine(listing.asin)
兑现诺言?而且,那个诺言会得到妥善解决或被否决吗?
读者注意事项-如果您阅读了所有注释,则可以看到OP的实际问题不在于Promise.all()
,但是由于发送请求到目标主机的速度太快,它们受到了速率的限制。由于那应该一直在传播应该很容易看到的请求错误,因此,OP显然也存在错误处理或传播问题,这很可能在此处未公开的代码中出现。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句