简体   繁体   English

Promise不会等待for循环完成

[英]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 - 我有一个异步代码,我想在我的一个节点js脚本中同步运行,但这不等待代码块完成并解析空对象 -

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

This is because your loop is generating new promises that are resolved asycnoursly, use Promise.all when you need to run multiple promises: 这是因为你的循环正在生成新的承诺,这些承诺是asycnoursly解决的,当你需要运行多个Promise.all时使用Promise.all

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM