Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promise doesn't wait a for loop to complete

I have a asynchronous code which I want to run synchronously in one of my node js script, But this doesn't wait for the code block to complete and resolves the empty object -

new Promise((resolve, reject) => {
if (object.email !== undefined) {
    for (let i = 0; i <= object.email.length; i++) {
        let emailObject = object.email[i]
        if (emailObject !== undefined) {
            this.isEmailUnsubscribed(emailObject, options).then(result => {
                console.log('>> isEmailUnsubscribed result in send email notification: ' + result)
                if (!result) {
                    emailObjects.push(emailObject.EmailID)
                }
            })
        }
    }
    console.log('emailObjects')
    console.log(emailObjects)
    resolve(emailObjects)
}
}).then(emailObjects => {
    object.email = emailObjects
    console.log('Email Objects from rules.evaluate')
    console.log(emailObjects) // At this point my object is always empty.
    this.sendEmailToSelectedUsers(object, options)
})
like image 645
Jeet Avatar asked Dec 15 '17 14:12

Jeet


People also ask

How do I resolve a promise in a for loop?

To use Javascript promises in a for loop, use async / await . This waits for each promiseAction to complete before continuing to the next iteration in the loop. In this guide, you learn how async/await works and how it solves the problem of using promises in for loops.

Does promise all wait for all promises?

Promise.all waits for all fulfillments (or the first rejection).

How do you wait for promise to end?

You can use the async/await syntax or call the . then() method on a promise to wait for it to resolve. Inside of functions marked with the async keyword, you can use await to wait for the promises to resolve before continuing to the next line of the function.

Does await wait for promise to resolve?

The await operator is used to wait for a Promise and get its fulfillment value. It can only be used inside an async function or a JavaScript module.


1 Answers

This is because your loop is generating new promises that are resolved asycnoursly, use Promise.all when you need to run multiple promises:

For example:

if (object.email !== undefined) {
    return Promise.all(object.email.map( emailObject => {
        if(emailObject){
            return this.isEmailUnsubscribed(emailObject, options)
        }else{
            return Promise.resolve()
        }
    } ))
    .then(emailObjects => {
        object.email = emailObjects
        console.log('Email Objects from rules.evaluate')
        console.log(emailObjects) // At this point my object is always empty.
        this.sendEmailToSelectedUsers(object, options)
    })
}
like image 170
asosnovsky Avatar answered Oct 02 '22 22:10

asosnovsky