use*_*205 6 javascript asynchronous node.js
我正在尝试为从数据库中获取的列表中的一堆项执行异步例程,但是我无法理解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);
});
});
}
Run Code Online (Sandbox Code Playgroud)
现在,我在日志中唯一得到的是
~~~现在更新Amazon API的所有上市价格~~~
我已经尝试将一个日志片段添加到被调用的例程中,并且所有例程都成功运行并记录它们应该是什么,但是promise.all.then不会执行.
我试过这样做:
Promise.all(bleh).then(console.log("我们做到了"));
这工作,但当我把一个功能放在然后,什么都没有运行.
请帮忙!
Promise.all()本身很简单.你传递了一系列的承诺.它返回一个新的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
});
Run Code Online (Sandbox Code Playgroud)
Promise.all()可能在您的代码中无效的一些原因:
Promise.all()永远不会解析/拒绝其主承诺.then()您应该处理的处理程序你的例子:
Promise.all(bleh).then(console.log("We did it"));
Run Code Online (Sandbox Code Playgroud)
是错的.您必须传递一个函数引用,.then()如下所示:
Promise.all(bleh).then(function() {
console.log("We did it")
});
Run Code Online (Sandbox Code Playgroud)
在您的情况下,console.log()将立即执行,而不是等待承诺得到解决.
在您的详细代码中,您100%确定:
listing_helper.listingPriceUpdateRoutine(listing.asin)
Run Code Online (Sandbox Code Playgroud)
正在回复一个承诺?并且,该承诺将得到妥善解决或拒绝?
读者注意事项 - 如果您阅读了所有评论,您可以看到OP的实际问题没有Promise.all(),但是他们因为向目标主机发送请求过快而受到限制.由于应该已经传播了应该很容易看到的请求错误,因此OP显然也存在错误处理或传播的问题,这可能在此处未公开的代码中.
| 归档时间: |
|
| 查看次数: |
702 次 |
| 最近记录: |