function inside function is not waiting for promise in javascript

坚强是说给别人听的谎言 提交于 2021-01-29 13:03:12

问题


Sorry if my title is not very explicit I dont know how to explain this properly. I am trying to use the distinct function for my app that uses loopback 3 and mongodb. It seems to work right but my endpoint wont hit the return inside my function. This is my code

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 [];

If I uncomment the return [] it will send the return and later it will show the should be last, so even when I dont have the return it seems to finish. It is now waiting for the response. I dont like the way my code looks so any pointer of how to make this look better I will take it.


回答1:


It looks like the sellerCollection.distinct takes a callback as one of it's parameters, therefore, you cannot use async/await with a callback-style function, since it's not a promise.

I would suggest turning this call into a promise if you'd like to use 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);
      }
    )
  })
}

Then, you can use this new function with async/await like such:

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
  }
}


来源:https://stackoverflow.com/questions/57486664/function-inside-function-is-not-waiting-for-promise-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!