Promise不会等待for循环完成

时间:2017-12-15 14:01:20

标签: javascript node.js promise

我有一个异步代码,我希望在我的一个节点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)
})

1 个答案:

答案 0 :(得分:7)

这是因为你的循环正在生成新的承诺,这些承诺是asycnoursly解决的,当你需要运行多个promise时使用Promise.all

例如:

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