下面我用一个数组调用 addUpdateDailyLeads
[{
"yyyymmdd": "20191124",
"admin_login":"rasheed.s",
"category":"PO",
"amount":10,
"office_id":10000,
"new_leads_attempted":10
},
{
"yyyymmdd": "20191124",
"admin_login":"rasheed.s",
"category":"PO",
"amount":10,
"office_id":10000,
"new_leads_attempted":10
},
{
"yyyymmdd": "20191125",
"admin_login":"prajeed.av",
"category":"FHL",
"amount":10,
"office_id":10000,
"new_leads_attempted":10
}
]
因此,键 0 应该插入,键 1 应该更新,因为重复键约束,键 2 将插入,
但我在键 1 上遇到重复键约束错误,因为数组映射不等待执行查询。
const addUpdateDailyLeads = async (req, res) => {
let admin_login,category,office_id,new_leads_attempted,yyyymmdd,where,values;
let data = req.body;
req.body.map(async function(item,i){
admin_login = item.admin_login,
category = item.category,
office_id = item.office_id,
new_leads_attempted = item.new_leads_attempted,
yyyymmdd = item.yyyymmdd;
where = {yyyymmdd:yyyymmdd, admin_login:admin_login, category:category};
values = {yyyymmdd:yyyymmdd, admin_login:admin_login, category:category,office_id:office_id,new_leads_attempted:new_leads_attempted,update_date:moment().format('YYYYMMDDHHmmss')};
console.log("calling ",i);
let chck = await addUpdateDailyLeadsCollection({where:where,values:values})
console.log("")
console.log("called")
})
res.json({ code: '200', message: `Advisor Daily Leads Updated ${admin_login}` });
}
const addUpdateDailyLeadsCollection = async data => {
let transaction;
let where = data.where
let values = data.values
var Sequelize = require("sequelize");
console.log("startef 1");
await AdvisorLeads.findOne({ where: where }, { useMaster: true }).then( async(data)=>{
console.log("waited");
if(data){
await data.update({new_leads_attempted: Sequelize.literal('new_leads_attempted + '+values.new_leads_attempted)}).then(data=>{
console.log("updated")
return Promise.resolve(1);
})
}else{
AdvisorLeads.create(values).then(data=>{
console.log("inserted")
return Promise.resolve(1);
})
}
})
};
控制台上的最终输出
calling 0
startef 1
waiting 1
calling 1
startef 1
waiting 1
calling 2
startef 1
waiting 1
waited
waited
waited
called
called
called
inserted
inserted
My expected output like
calling 0
startef 1
waiting 1
waited
inserted
called
calling 1
startef 1
waiting 1
waited
updated
called
calling 2
startef 1
waiting 1
waited
inserted
called
最后我需要的是等待每个项目,执行所有查询,然后处理下一个项目