Node JS异步承诺.所有问题

Node JS Async Promise.All issues

本文关键字:有问题 承诺 异步 JS Node      更新时间:2023-09-26

我正试图为从数据库中获得的列表中的一堆项目执行异步例程,但我很难理解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中放入一个函数时,什么都不会运行。

请帮忙!

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

  1. 你没有向它传递一系列承诺
  2. 您传递的数组中的某些promise从不解析或拒绝,因此Promise.all()从不解析/拒绝其主promise
  3. 您没有正确地将回调传递到.then()处理程序,而您应该在那里
  4. 您没有正确地从内部函数返回promise,因此它们正确地向外传播或连锁

你的例子:

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