node.js将我的express方法转换为async / await

时间:2018-04-23 18:07:40

标签: node.js express async-await

我怀疑将我的express方法转换为使用async / await。

此时,我的方法如下:

app.post('/', (req, res) => {
const body = req.body;

let hospital = new Hospital({
    name: body.name,
    user: req.user._id
});

hospital.save((err, hospitalCreated) => {
    if (err) {
        return res.status(400).json({
            ok: false,
            mensagem: "Error to create hospital",
            errors: err
        });
    }

    res.status(201).json({
        ok: true,
        hospital: hospitalCreated
    });
});

});

作为节点的新手,我试着这样说:

app.post('/', async (req, res) => {
const body = req.body;

let hospital = new Hospital({
    name: body.name,
    user: req.user._id
});

await hospital.save((err, hospitalCreated) => {
    if (err) {
        return res.status(400).json({
            ok: false,
            mensagem: "Error to create hospital",
            errors: err
        });
    }

    res.status(201).json({
        ok: true,
        hospital: hospitalCreated
    });
});

这是实现这一目标的正确方法吗?我必须使用try / catch吗?什么是最好的方法?

由于

2 个答案:

答案 0 :(得分:1)

asyncawait生成器的目的是避免使用回调。如果save方法总是返回Promise并调用回调,那么您所做的工作可能会奏效,但这种方法会破坏生成器的整个目的。您应该删除回调并改为使用trycatch

try {
    await hospital.save();
    res.status(201).json({
        ok: true,
        hospital: hospital
    });
} catch (err) {
    res.status(400).json({
        ok: false,
        mensagem: "Error to create hospital",
        errors: err
    });
}

答案 1 :(得分:0)

我认为您可以使用Promise解析将hospital.save移动到异步函数,然后使用await获取响应并捕获以从promise中获取错误,例如:

使用mongoose回调更新:

function saveHospital(hospital) {
        return new Promise((resolve, reject) => {
            hospital.save((err, hospitalCreated) => {
                if (err) {
                    reject(error);
                }

                resolve(hospitalCreated);
            });
        });
    }

    app.post('/', async (req, res) => {
        const body = req.body;

        let hospital = new Hospital({
            name: body.name,
            user: req.user._id
        });

        try {
            const hospitalCreated = await saveHospital(hospital)

            res.status(201).json({
                ok: true,
                hospital: hospitalCreated
            });
        } catch(error) {
            res.status(400).json({
                ok: false,
                mensagem: "Error to create hospital",
                errors: err
            })
        }
    }