Pankaj Sharma Pankaj Sharma - 3 days ago 6
Javascript Question

How to Send response after for each loop completed

Response.json should execute after foreach loop completes its execution



var todoarr = (req.body.data) ? req.body.data : undefined
todoarr.forEach(function(element) {
if(element.done == true) {
TodoService.removeTodo(element, function(success) {
});
}
});
res.json("success");




Answer

You can try to use async.js http://caolan.github.io/async/ .

each method http://caolan.github.io/async/docs.html#each

Or you can try use Promise.all.

For example:

let promiseArr = [];
todoarr.forEach(function(element) {
     if(element.done == true) {
         promiseArr.push(somePromiseMethod(element)); 
     }
}); 
//now execute promise all
Promise.all(promiseArr)
.then((result) => res.send("success"))
.catch((err) => res.send(err));

More info here. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

Some promise example:

function somePromiseMethod(element) {
   return new Promise((resolve,reject) => {
      TodoService.removeTodo(element, function(success) {
            resolve();
         });
   });    
}

Hope this helps.

Comments