首页 > 解决方案 > 在 Javascript/Nodejs、Mongoose 中链接多个异步函数,其中一个函数依赖于另一个函数

问题描述

我有两个相互依赖的功能。在我的用户保存他的个人资料后,我首先有一个函数来保存他的位置,然后返回它的 id,然后我用它来更新用户。但是在尝试了很多组合之后,我无法让它正常工作。我将在下面列出我尝试过的内容。

async function NewUserProfileUpdate(req) {
    try {
        const loc_id = LocationController.AddUserLocation(req.body.location.longitude
            , req.body.location.latitude, req.query.id)

        loc_id.then((id) => {
            logger.info("Then " + id)
            UserModel.User.updateOne({ user_id: req.query.id }, {
                gender: req.body.gender, name: req.body.name, bio: req.body.bio,
                location_id: id
            })
        })

    } catch (err) {
        return err
    }
}
async function AddUserLocation(longitude, latitude, userID) {
    const location = { type: 'Point', coordinates: [longitude, latitude] }

    await LocationModel.create(
        { user_id: userID, location: location }, function (err, loc) {
            if (err) {
                return err;
            }
            logger.info("Created + " + loc._id)
            return loc._id
        });
}

然后在创建之前调用

info: Then undefined {"service":"user-service"}
info: Created + 5feb3174f70c08f9543fdc49 {"service":"user-service"}

我尝试使用事件,用 then => 链接它,用异步链接(idk 为什么这不起作用,我有 loc_id 的异步,应该等到 loc_id 返回但它没有),我尝试了常规函数和异步的不同组合但是什么都没有给我想要的结果。(我使用异步和事件得到了结果,但没有监听器,我不知道那里发生了什么)

标签: javascriptnode.jsasynchronousmongooseasync-await

解决方案


如果你正在使用async/ await,你不应该使用.then()也不能将回调传递给 mongoose 方法,以便它们返回可行的await承诺。

async function NewUserProfileUpdate(req) {
    const location_id = await LocationController.AddUserLocation(req.body.location, req.query.id);
//                      ^^^^^
    logger.info("Then " + location_id);

    await UserModel.User.updateOne({ user_id: req.query.id }, {
//  ^^^^^
        gender: req.body.gender,
        name: req.body.name,
        bio: req.body.bio,
        location_id,
    });
}

async function AddUserLocation({longitude, latitude}, user_id) {
    const location = { type: 'Point', coordinates: [longitude, latitude] };

    const loc = await LocationModel.create({ user_id, location });
//                                                              ^ no callback
    logger.info("Created + " + loc._id);

    return loc._id;
}

推荐阅读