1

I'm using lodash _.forEach loop and inside _.forEach loop i'm using multiple promise and putting inside array promises. using sendEmailApi method I'm sending email to users, My requirement is if i get any error from I want to exit from outer _.forEach loop , dont want to process all promises. code below written but not working , it's processing the whole _.forEach loop if i get any error from in the middle of loop

_.forEach(result, function (value, index) {
    _.forEach(value, function (value1, index1) {
        if(!displayName)
            displayName = value1.displayname;
        productList += '"' + value1.productplannames + '",';
    });
    tempJsonStr = '{"email":"' + index + '","displayname":"' + displayName + '","productplannames":[' + _.trim(productList, ",") + ']}';
    console.log("tempJsonStr",tempJsonStr);
    productList ="";
    displayName="";
    promises.push(emailUtils.sendEmailApiProcess(JSON.parse(tempJsonStr),responsePayLoad,task,done).then(function () {
    }).catch(err => {
        console.log("errrrrrrrrr");
    return false;
    }))

});

Promise.all(promises).then(function () {
    console.log("All done");
});
Dev
  • 413
  • 10
  • 27
  • 3
    The `_.forEach()` loop finishes before any of the email requests have completed. – Pointy Jul 15 '17 at 15:52
  • 1
    Don't build your own JSON like this - use JSON.stringify, learn how promises work, learn how async code flows - read https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Benjamin Gruenbaum Jul 15 '17 at 15:59
  • You are initialising `productList` and `displayName` in a really weird sequence – Bergi Jul 16 '17 at 06:58
  • @Bergi do u have any other idea how to assign it – Dev Jul 16 '17 at 07:26
  • Well you should *declare* them with `var`, and you should initialise them before the loop that appends to them. – Bergi Jul 16 '17 at 09:03
  • @Bergi its already done in my code, full code is not here, this is sample. – Dev Jul 16 '17 at 12:40
  • Well we can only criticise whatever you post here, so you better always post your actual code :-) – Bergi Jul 16 '17 at 12:46

1 Answers1

0

Because of asynchronous behavior of Promise, the classic foreach loop will not wait until each of the Promises resolves/rejects. Hence, you cannot be sure at the end of each iteration that the Promise is not pending anymore.

bluebird's implementation of Promise has a neat function for this: Promise.each, which will wait until the Promise resolves/rejects: http://bluebirdjs.com/docs/api/promise.each.html

cassini
  • 365
  • 1
  • 7
  • can u pls share some sample promise each code for my code – Dev Jul 16 '17 at 05:48
  • I want to break the promise as soon as i get any reject from one promise, dont want to process all promise – Dev Jul 16 '17 at 07:28