我正在传递mongoose promises数组,由于某种原因,有时customerFindPromise返回null,有时它会返回请求的对象。我在这里做错了什么
******************** START result0: null result END ********************
******************** START result1: { _id: 5a18a637346826574416a588,
doc_fname: 'Bob',
doc_lname: 'Smith',
numOfCases: 1,
__v: 0 } result END ********************
******************** START result2: {"n":1,"ok":1} result END ********************
代码
var customer = {
doctor_id: 5a18a637346826574416a588,
cust_fname: 'dfsdf',
cust_lname: 'sdasd',
case_type: 'Crowns',
_id: 5a1cd19438f14164b0087753
}
test(customerCase);
async function test(customerCase) {
console.log("******************** customerCaseDelete: "+ customerCase._id +" ********************");
var _id = customerCase._id;
var doctor_id = customerCase.doctor_id;
var query = {_id:_id};
const customerFindPromise = CustomerCases.findById(_id);
const customerRemovePromise = CustomerCases.remove(query);
const doctorUpdatePromise = Doctors.findOneAndUpdate({_id:doctor_id},{'$inc': {'numOfCases': -1}},{new:true});
await Promise.all([customerFindPromise,doctorUpdatePromise,customerRemovePromise])
.then((result) => {
console.log("******************** START result0: "+ result[0] +" result END ********************");
console.log("******************** START result1: "+ result[1] +" result END ********************");
console.log("******************** START result2: "+ result[2] +" result END ********************");
res.json(result);
}).catch((err) => {
console.log("******************** START err: "+ err +" err END ********************");
throw err;
});
}
答案 0 :(得分:0)
您运行的功能是异步的,并不总是按顺序运行。 Promise.all
也不会改变承诺的执行顺序,它只是等待它们全部被解决。
有时CustomerCases.remove
会在CustomerCases.findById
之前执行并解决,因此null
会在首先删除文档时解析。
等待承诺在执行下一个查询之前连续解析,当您使用async
/ await
时,可以相当简单地添加:
try{
let find = await CustomerCases.findById(_id)
console.log(`find: ${find}`)
let update = await CustomerCases.remove(query)
console.log(`update: ${update}`)
let remove = await Doctors.findOneAndUpdate({_id:doctor_id},{'$inc': {'numOfCases': -1}},{new:true})
console.log(`remove: ${update}`)
res.json([find, update, remove])
} catch(err) {
console.error(err)
throw err // next(err)?
}
如果需要串行执行助手,请尝试bluebirds Promise.each
。