如何将猫鼬的PROMISE链交易迁移到ASYNC / AWAIT流?

时间:2019-07-03 15:26:23

标签: javascript promise async-await

我创建了一个将数据库响应集成到Promise流中的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 }));
});

致谢。

2 个答案:

答案 0 :(得分:0)

您可以简单地使诺言运行的函数异步运行,因此,您可以等待诺言得以解决。

例如,在您的路线中使用此:

router.post('/', async (req, res) => {

,然后在执行异步操作时,使用以下方法:

const company = await Companies.findOne({ _id: idCompany }).exec();

此外,我建议您使用try and catch语句将其包装

希望有帮助!

答案 1 :(得分:0)

将诺言与猫鼬一起使用的一个关键是使用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块中引发一些特定的自定义错误。