【问题标题】:function inside function is not waiting for promise in javascript函数内部的函数不等待javascript中的承诺
【发布时间】:2019-08-15 06:11:31
【问题描述】:

对不起,如果我的标题不是很明确,我不知道如何正确解释。 我正在尝试为使用 loopback 3 和 mongodb 的应用程序使用 distinct 函数。它似乎工作正常,但我的端点不会在我的函数内返回。 这是我的代码

const distinctUsers = await  sellerCollection.distinct('userId',{
      hostId : host.id,
      eventId:{
        "$ne" : eventId
      }
    }, async function (err, userIds) {;

      if(!userIds || userIds.length ==0)
        return [];

      const filter = {
        where:{
          id: {
            inq: userIds
          }
        }
      };
      console.log("should be last")
      return await BPUser.find(filter);
    });
    console.log(distinctUsers);
    console.log("wtf??");
    //return [];

如果我取消对 return [] 的注释,它会发送 return,然后它会显示应该是最后一个,所以即使我没有 return,它似乎也完成了。它现在正在等待响应。我不喜欢我的代码看起来的样子,所以任何关于如何使它看起来更好的指针我都会接受它。

【问题讨论】:

  • sellerCollection 到底是什么东西?如果它不期望 async 函数,则可能无法正常工作。
  • sellerCollection.distinct 极不可能采用节点样式的异步回调并返回 Promise - 很少看到这样的东西 - 此外,您在代码中有一个流浪的 ;

标签: javascript loopback


【解决方案1】:

看起来sellerCollection.distinct 将回调作为其参数之一,因此,您不能async/await 与回调样式函数一起使用,因为它不是承诺。

如果你想使用async/await,我建议把这个电话变成一个承诺:

function findDistinct(hostId, eventId) {
  return new Promise((resolve, reject) => {
    sellerCollection.distinct(
      'userId', 
      { hostId, eventId: { "$ne": eventId } },
      function (error, userIds) {
        if (error) { 
          reject(error); 
          return; 
        }
        if (!userIds || userIds.length === 0) {
          resolve([]);
          return;
        }
        resolve(userIds);
      }
    )
  })
}

然后,您可以像这样将这个新功能与async/await 一起使用:

async function getDistinctUsers() {
  try {
    const hostId = ...
    const eventId = ...

    const distinctUsers = await findDistinct(hostId, eventId)

    if (distinctUsers.length === 0) {
      return
    }

    const filter = {
      where: {
        id: { inq: userIds }
      }
    }
    const bpUsers = await BPUser.find(filter) // assuming it's a promise

    console.log(bpUsers)
  } catch (error) {
    // handle error
  }
}

【讨论】:

  • 嗨,我认为这会起作用,但似乎辅助函数上发生的事情似乎在另一个线程 idk 上运行。我做了这个 console.log("a1"); const distinctUsers = await findDistinct (sellerCollection, host.id, eventId); console.log({"aaa": distinctUsers});它不会传递给第二个 console.log。
  • @JuanDiego 我刚刚意识到我在findDistinct 函数中犯了一个错误,对不起,请用我所做的更改重试
猜你喜欢
  • 2018-02-03
  • 2021-01-18
  • 1970-01-01
  • 2020-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-23
  • 1970-01-01
相关资源
最近更新 更多