首页 > 解决方案 > Foreach 无法将每条记录推送到 NodeJS 中的 promise 函数

问题描述

parse().then(function (contacts) {
    contacts.forEach(cont => {
        cont.id,
            cont.first_name,
            cont.last_name,
            cont.phone_numbers,
            cont.organization_name,
            cont.email

        appoloemail = cont.email;
        fullname = cont.first_name + ' ' + cont.last_name;

        deal = cont.first_name + ' Deal';
        dealname = deal;
        orgname = cont.organization_name;
        title = cont.title;
 console.log('ORG NAME in Start:', orgname)
        console.log('Full Name: ', fullname)
        console.log('Email', appoloemail);
        console.log('Custom Time: ', newbacktime);
        console.log('Contact Update Time: ', contact_updatedate);

       create_org(orgname)
            .then(function (orgid) {
                console.log('Org Id Return:', orgid);
                globalorgid=orgid;
                console.log('In create org: ',globalorgid)
                createperson(fullname, orgid, appoloemail, apollophone)

            })
            .catch(function (err) {
                console.log('Error!', err);
            })
        //  }
console.log('Loop End::');
    })

}).catch(function (err) {
    console.log(err);
});

循环首先迭代每条记录,然后开始推送记录和 org 和 person,但 org 函数完成执行并推送所有 org 数据,但 create_person 推送数据位于 foreach 循环数组的最后一个索引中,并且每个 org 具有相同人名。

标签: node.jsjsonloopspromise

解决方案


然后你的部分create_org(orgname)遗嘱会及时执行。看起来你的变量是用 定义的var,而不是let。所以,要么你在里面定义你的变量forEachlet要么只是forEach用类似的东西替换

Promise.all(contacts.map(
        contact=>create_org(contact.organization_name)
        .then(orgid=>createperson(contact.first_name+' '+conact.last_name,orgid,contact.email,contact.phone_numbers))
    )
)

推荐阅读