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)
})
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.
Promise.all waits for all fulfillments (or the first rejection).
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.
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.
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)
})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With