我有一个函数,我需要带一些ids来使用acyn和await填充findOneAndUpdate im上的更新,但是findoneandupdate运行在其他的之前……不知道为什么
async function update(req, res) {
const update = req.body;
await Something1.findOne({
'id_Something1': update.something1_id
}).exec((err, something) => {
if (err || !something) {
return res.status(500).send({
message: 'Error'
})
}
update.something1= something._id;
});
await Collection.findOneAndUpdate({
'id_something1': update.custom_id
}, update, (err, Updated) => {
console.log('this should show after the first find but it doesnt');
if (err) {
return res.status(500).send({
error: err.errmsg
});
} else if (!sociosUpdated) {
return res.status(500).send({
message: 'Error'
});
}
res.status(200).send({
data_updated: Updated
});
});
};发布于 2019-12-04 13:59:54
问题是你在使用async/await的同时也在使用asynchronous。您可以尝试以下代码:
async function update(req, res) {
const update = req.body;
try {
const something = await Something1.findOne({
'id_Something1': update.something1_id
}).exec();
update.something1 = something && something._id;
const Updated = await Collection.findOneAndUpdate({
'id_something1': update.custom_id
}).exec();
return res.status(200).send({
data_updated: Updated
});
}
catch(err) {
return res.status(400).send(err);
}
});https://stackoverflow.com/questions/59169457
复制相似问题