温馨提示:本文翻译自stackoverflow.com,查看原文请点击:javascript - How to migrate my mongoose PROMISE chain transactions to ASYNC / AWAIT flow?

javascript - 如何将 Mongoose 的PROMISE链交易迁移到ASYNC / AWAIT流?

发布于 2020-03-27 11:58:37

我创建了一个在答应流程中集成数据库响应的API,但是我认为代码的解释很复杂,并且我认为异步/等待方法可以提高理解度和代码本身。

该API使用Mongoose 5.6.1和Express 4.17.1在NodeJS中构建。

您能帮我改善吗?

以下是我要改进的API:

/** New employee */
router.post('/', (req, res) => {
    let { idCompany, name, departament } = req.body;
    let _id = mongoose.Types.ObjectId(); // Generating new MongoDB _ID
    let employeeCreated;

    const promise1 = new Promise((resolve, reject) => {
        // Querying by document '$oid'
        Companies.findOne({ _id: idCompany }, (err, company) => {
            // Error returned
            if (err) reject({ error: "Invalid request, something went wrong!" });
            // Invalid data received
            if (!company) reject({ error: "Unauthorized action!" });
            // Everything OK
            resolve(company);

        });
    })
    .then(company => {
        if(company) {
            const promise2 = new Promise((resolve, reject) => {
                Employees.create({ _id, idCompany, name, departament }, (err, employee) => {
                    // Error returned
                    if (err) reject({ error: "Invalid request, something went wrong!", err });
                    // Everything OK
                    employeeCreated = employee;
                    resolve(company);
                });
            })
            return promise2;
        }else reject({ error: "Company not found!" });
    })
    .then(company => {
        let { name: companyName, address, email, tel, employees } = company;
        employees.push(_id);

        const promise3 = new Promise((resolve, reject) => {
            Companies.findByIdAndUpdate(
                { _id: idCompany },
                { $set: { _id: idCompany, name: companyName, address, email, tel, employees } }, // spotlight
                { new: true },
                (err, company) => {
                    // Something wrong happens
                    if (err) reject({ success: false, error: "Can't update company!" });
                    // Everything OK
                    resolve(company);
                }
            );
        });
        return promise3;
    });

    promise1
        .then(() => res.json({ success: true, employeeCreated }))
        .catch(err =>   res.status(400).json({ error: "Invalid request, something went wrong!", err }));
});

问候。

查看更多

查看更多

提问者
Caio_Barbosa
被浏览
35
trincot 2019-07-03 23:59

对 Mongoose 使用诺言的一个关键是使用以下exec方法:

然后,您的代码可能看起来像这样(未经测试):

router.post('/', async (req, res) => {
    try {
        const { idCompany, name, departament } = req.body;
        const _id = mongoose.Types.ObjectId();
        const company = await Companies.findOne({ _id: idCompany }).exec();
        const employeeCreated = await Employees.create({ _id, idCompany, name, departament });
        const { name: companyName, address, email, tel, employees } = company;
        employees.push(_id);
        await Companies.findByIdAndUpdate(
                    { _id: idCompany },
                    { $set: { _id: idCompany, name: companyName, address, email, tel, employees } }, // spotlight
                    { new: true }).exec();
        res.json({ success: true, employeeCreated });
    } catch(err) {
        res.status(400).json({ error: "Invalid request, something went wrong!", err });
    }
});

try如果发现必要,可以在块中引发一些特定的自定义错误

发布
问题

分享
好友

手机
浏览

扫码手机浏览