从 Mongoose Promise 中检索值作为回调

Retrieving value from Mongoose Promise as a callback

从猫鼬承诺中提取数据时遇到问题。我想使用适当的 ID 从 mongoose 中找到一组用户,并沿着承诺链传递结果。

查询正在从数据库中提取正确的数据。当我将查询嵌套在承诺链中然后尝试传递结果时,我的 console.log 显示 [Function (anonymous)]。是否有适当的结构可以使用 mongoose 从 MongoDB 中提取数据,然后沿着承诺链传递该数据?

承诺链:

addItem(guildId, items, timeCreated) {
    return new Promise((resolve, reject) => {
        // other functionality omitted for brevity
        resolve(guildId, items, timeCreated);
    }).then((guild, item, timeCreate) => {
        findGroupUsers(guild).then((response) => {
            return new Promise((resolve, reject) => {
                console.log(response.userId);
                resolve(response);
            });
        });

猫鼬查询:


const findGroupUsers = async (guildId) => {
    const members = await EngagementTracking.find({ guildId: `${guildId}` }).exec();
    console.log(members);
    return members;
};

已验证的答案成功从 addItem 内部的查询中提取数据。为了继续并沿链传递查询的 结果 ,我执行了以下操作:

addItem(guildId, items, timeCreated) {
    return new Promise((resolve, reject) => {
//other functionality
        resolve(guildId, items, timeCreated);
    }).then((guild, items, timeCreate) => {
        return findGroupUsers(guild).then((response) => {
            return new Promise((resolve) => { resolve(response); });
        });
    }).then((data) =>{// other functionality //});

你的 add item 函数看起来有点奇怪你应该这样做:

addItem(guildId, items, timeCreated) {
    return new Promise((resolve, reject) => {
        // other functionality omitted for brevity
        resolve(guildId, items, timeCreated);
    }).then((guild, predict, timeCreate) => {
        return findGroupUsers(guild).then((response) => {
          console.log(response.userId);
          return response;
        });

您不需要 return .then 中的新承诺 还要注意你应该 return 你的承诺(你没有 return findGroupUser)

最后你应该有一个 addItem.then(/do something/) 或 await