5
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?

2
  • Please format/indent your code properly to make it readable. Commented Apr 23, 2016 at 17:25
  • You pass an array of promises to Promise.all(). You do not pass a function to Promise.all(). There are also no asynchronous operations in the code you show so there is no reason to use promises at all. You can just code a regular loop. Commented Apr 23, 2016 at 17:25

1 Answer 1

34

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
});
Sign up to request clarification or add additional context in comments.

1 Comment

Great answer! Just for those of us who don't know Promise.all: if it fulfills it returns an array of the values from the fulfilled promises in the same order as defined in the iterable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.