Search code examples
javascriptloopback

function inside function is not waiting for promise in javascript


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.


Solution

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