简体   繁体   English

Promise.all不要等待所有承诺解决

[英]Promise.all do not wait all promises to resolve

I need to get data in parallel, and then calculate with them simultaneously, with Node.js. 我需要并行获取数据,然后使用Node.js同时使用它们进行计算。

So I use promise.all, but it behaves strange. 所以我使用promise.all,但它表现得很奇怪。 When I launch it the first time, the calculations are longer and it fails just after the first promise has resolved, even if the others succeed. 当我第一次启动时,计算时间会更长,并且在第一个承诺解决之后就会失败,即使其他承诺成功。 When I launch it the second time, it's faster because all data are stored in the database, so it succeeds. 当我第二次启动它时,速度更快,因为所有数据都存储在数据库中,所以它成功了。 I really don't understand. 我真的不明白。 Here is my code : 这是我的代码:

var Promise = require('promise');
/* The list of objects */
var ingrd_list = JSON.parse(req.body.ingrd_list);
/* func.addFood is my function to apply on. It takes a callback parameter as last parameter */
var pAddFood = Promise.denodeify(func.addFood);
var pArray = [];

ingrd_list.forEach(function(ingrd){
    var my_p = pAddFood(ingrd);
    pArray.push(my_p);
    });

Promise.all(pArray).then(function(){
    console.log("success !");
    })
    .catch(function(){
            console.log("failure !");
    });

I have defined the addFood function in an other file, like this : 我在另一个文件中定义了addFood函数,如下所示:

exports.addFood = function(ingrd, cb){
        /* Some code */
    cb(data.id);
});

I want to apply this function, so I tried to make it "denodeify-compatible". 我想应用这个功能,所以我试着让它“与denodeify兼容”。 But it doesn't work as expected. 但它没有按预期工作。 Any help would be greatly appreciated 任何帮助将不胜感激

The problem is that denodeify expect your callback to be called in a standard way, that is callback(err, data) 问题是denodeify期望以标准方式callback(err, data) ,即callback(err, data)

but you are calling you callback with callback(data) , so it is putting your promise in a rejected state, because it thinks that you data is in fact the error, thus Promise.all fails 但是你用callback(data)函数调用callback(data) ,所以它将你的承诺置于被拒绝的状态,因为它认为你的数据实际上是错误,因此Promise.all失败了

To fix that you should modify you addFood function to call the callback like this cb(undefined, data.id); 要解决这个问题,你应该修改你的addFood函数来调用这个回调就像这个cb(undefined, data.id);

ps: you can look for "node style callback" if you want more detailed information about this callback style ps:如果您想了解有关此回调样式的更多详细信息,可以查找“节点样式回调”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM