使用异步/回调获取数据?

时间:2020-08-05 16:59:18

标签: javascript node.js async-await

我不知道如何将其转换为异步类型。我该如何转换呢?这是代码

router.put('/unfollow', requireLogin, (req, res) => {
    User.findByIdAndUpdate(req.body.unfollowId, { 
        $pull: {followers: req.user._id}
    },{
        new: true
    },(err, result) => {
        if(err) return res.status(422).json({ error: err })
        User.findByIdAndUpdate(req.user._id, {
            $pull: { following: req.body.unfollowId }
        }, {
            new: true
        })
            .select('-password')
            .then(result => {
                res.json(result)
            })
            .catch(err => {
                return res.status(422).json({ error: err })
            })
    })
})

2 个答案:

答案 0 :(得分:0)

我认为您可以这样做:

router.put('/unfollow', requireLogin, async (req, res) => {
    try {
        await User.findByIdAndUpdate(req.body.unfollowId, {$pull: {followers: req.user._id}}, {new: true});
        const result = await User.findByIdAndUpdate(req.user._id, {$pull: {following: req.body.unfollowId}}, {new: true})
            .select('-password');
        res.json(result);
    } catch (err) {
        return res.status(422).json({error: err});
    }
});

答案 1 :(得分:0)

这行吗?

router.put('/unfollow', requireLogin, async (req, res) => {
await User.findByIdAndUpdate(req.body.unfollowId, { 
    $pull: {followers: req.user._id}
},{
    new: true
},(err, result) => {
    if(err) return res.status(422).json({ error: err })
    await User.findByIdAndUpdate(req.user._id, {
        $pull: { following: req.body.unfollowId }
    }, {
        new: true
    })
        .select('-password')
        .then(result => {
            res.json(result)
        })
        .catch(err => {
            return res.status(422).json({ error: err })
        })
})

})