node.js - 如何避免多个 Mongoose 操作的嵌套承诺?
问题描述
很抱歉,我知道已经有一些帖子处理 NodeJS 中的嵌套承诺问题,但我仍然无法理解这一点。
我正在使用 Express 和 Mongoose,我想找到一个对象 ID,然后保存一个对象,然后更新另一个对象,但我不明白我应该如何做得比这更好,因为这些是依赖的承诺:
// Get Client object ID from email
Client.findOne({ email: req.body.clientEmail })
.exec()
.then((client) => {
// Then add Client ID to program and save
const program = new Program(req.body);
program.Client = client._id;
program.save()
// Finally add the program to the existing coach user
.then((program) => {
Coach.updateOne({ _id: req.session.userId }, { $push: { programs: program._id } },
function (err, coachUpdated) {
if (err) return handleError(err);
console.log(coachUpdated);
})
})
.then(() => { res.send('New program added!'); });
})
提前致谢
解决方案
简单,使用async/await
我会做类似的事情
const client = await Client.findOne({ email: req.body.clientEmail })
.exec();
const program = new Program(req.body);
program.Client = client._id;
const {_id} = await program.save();
//If this is not a promise. you can still use `promisify` from `utils` standard node.js lib to make it a promise
// and then call it with await. :)
Coach.updateOne({ _id: req.session.userId }, { $push: { programs: _id } },
function (err, coachUpdated) {
if (err) return handleError(err);
console.log(coachUpdated);
})
//You can choose to place it inside the callback above.
res.send('New program added!');
注意:外包装函数应以async
like为前缀async function (req, res) {...