The promise does not wait for the completion of the cycle

I have asynchronous code that I want to run synchronously in one of my node js script, but this does not wait until the code block completes and the empty object resolves -

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)
})
+4
source share
1 answer

This is because your loop generates new promises, which is allowed asycnoursly, use Promise.allwhen you need to run multiple promises:

For instance:

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)
    })
}
+7
source

Source: https://habr.com/ru/post/1690859/


All Articles