Node JS Async Promise.All问题

时间:2016-04-30 17:10:29

标签: javascript node.js 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);
        });
    });
}

现在,我在日志中唯一得到的是

  

~~~现在更新Amazon API的所有上市价格~~~

我已经尝试将一个日志文件添加到被调用的例程中,并且所有例程都成功运行并记录它们应该是什么,但是promise.all.then不会执行。

我尝试过这样做:

  

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

这很有效,但当我在Then中放入一个函数时,没有任何东西可以运行。

请帮忙!

1 个答案:

答案 0 :(得分:6)

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
});

Promise.all()可能无法在您的代码中使用的一些原因:

  1. 你没有向它传递一系列承诺。
  2. 您传递的数组中的某些承诺永远不会解决或拒绝,因此Promise.all()永远无法解决/拒绝其主承诺
  3. 您没有正确地将回调传递给您应该
  4. .then()处理程序
  5. 您没有正确地从内部函数返回承诺,因此它们会传播或正确链接
  6. 你的例子:

    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显然也有错误处理或传播的问题,这可能在这里没有公开的代码中。