Reputation: 5659
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)
})
Upvotes: 5
Views: 952
Reputation: 2235
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)
})
}
Upvotes: 7