node.js - 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 具有相同人名。
解决方案
然后你的部分create_org(orgname)
遗嘱会及时执行。看起来你的变量是用 定义的var
,而不是let
。所以,要么你在里面定义你的变量forEach
,let
要么只是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))
)
)
推荐阅读
- typescript - fp-ts 在管道中间使用异步函数
- mongodb - Mongodb排序问题
- rstudio - 具有数值和分类变量的 DBSCAN 聚类
- mysql - 如何使用 sql 从此表中获取总约会持续时间
- javascript - 如何在 CKEditor 文件上传 url 中发送 api 令牌?
- ios - 如何在 Objective-C 中从 NSOutputStream 获取图像
- python - 如何在 Python 中获取宏弹出错误消息
- javascript - 如何在没有 SVG 代码的情况下将 SVG 颜色作为附加图像进行操作?
- regex - 如何在 Tcl 中使用“regsub”或“regex”从“开始”期间删除前导和尾随字符
- python-3.x - 无法从另一个文件调用变量