节点JSasynchronousPromise.All问题

我试图从列表中的一堆项目执行asynchronous例程,但是我很难理解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的所有上市价格~~~

我已经尝试在被调用的例程中添加日志logging,并且所有例程都成功运行并logging他们应该logging的内容,但promise.all.then不会执行。

我试过只是在做:

Promise.all(bleh).then(console.log(“我们做了”));

这工作,但是当我把一个函数然后,没有任何运行。

请帮忙!

Promise.all()本身很简单。 你传递了一系列的承诺。 它返回一个新的承诺,当数组中的所有承诺解决或将拒绝数组中的任何单个承诺拒绝时,将解决。

 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()在你的代码中可能不起作用的一些原因:

  1. 你没有向它传递一系列的承诺。
  2. 您传递的数组中的某些promise不会parsing或拒绝,因此Promise.all()永远不会parsing/拒绝它的主承诺
  3. 你没有正确地将callback传递给.then()处理程序
  4. 你没有正确地从内部函数返回承诺,所以他们传播出去或正确链接

你的例子:

 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显然也存在error handling或传播的问题,这在代码中很可能没有公开。