与猫鼬异步等待返回空对象

时间:2018-10-04 04:50:55

标签: express async-await es6-promise

我有一个用于用户个人资料的猫鼬模式,他们可以在其中添加工作经验(当前为模式中的对象数组)。

我已经使用以下代码查找用户的个人资料,并获得体验对象作为输入,然后将其附加到架构中的数组,并返回具有经验的保存的个人资料:

Router.post('/experience',
Passport.authenticate('jwt', {session: false}), async (req, res) => {
try {
    const myProfile = await Profile.findOne({user: req.user._id});

    if (myProfile) {
        const exp = {
            title: req.body.title,
            company: req.body.company,
            location: req.body.location,
            from: req.body.from,
            to: req.body.to,
            isCurrent: req.body.isCurrent,
            description: req.body.description
        };
        // add to Profile experience array
        Profile.experience.unshift(exp); // adds to beginning of array
        const savedProfile = await Profile.save(); // have also tried myProfile.save() but that doesn't work too
        if (savedProfile) {
            console.log(savedProfile);
            res.json({message: `Profile Updated Successfully`, details: savedProfile})
        }
        else { throw `Experience Details Not Saved`}
    }

} catch (err) { res.json(err); }
});

这里的问题是响应始终是一个空对象,当我检查数据库时,没有保存任何经验。此代码是否错误?同样的事情适用于Promises,但我想尝试一种新的做事方式。

1 个答案:

答案 0 :(得分:0)

async-await模式是另一种写入Promise的方式,该函数的返回值是整个异步的Promise.resolve(result)Promise.reject(reason)

在外部函数Router.post中,它必须使用async-await模式的thenPromise模式来处理返回的{{1} }。否则,Promise函数将没有机会运行,因为返回的async将被省略。

相关问题