Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

promise in loop in node.js

Promise.all(function(){
    for(var numb in req.body){
        console.log(numb+":"+req.body[numb]);
        checkValue(numb,function(err,result){
            if(result){
                console.log(result);
                send[result]="true";
                console.log(send);
            }
            if(err){console.log(err+"not");}
        });
    }   
}).then(res.json(send));

I want to execute the for loop first and then send the data back. I am trying to use promise.all but I am not sure if its correct. could someone help me out?

like image 301
sachin hunur Avatar asked Nov 28 '22 04:11

sachin hunur


1 Answers

If you're using Promises, check out this

you can just fix this by doing the following:

var promises = [];

for(var numb in req.body)
{
    promises.push(checkValue(numb));
}

Promise.all(promises)    
 .then(function(data){ /* do stuff when success */ })
 .catch(function(err){ /* error handling */ });

function checkValue(numb){
 return new Promise(function(resolve, reject){
  // place here your logic
  // return resolve([result object]) in case of success
  // return reject([error object]) in case of error
});
like image 155
smeedten Avatar answered Dec 04 '22 08:12

smeedten