-2

I am trying to write a reusable function that doesn't return until it has resolved promise from a mongodb query. I can nearly achieve this using a IIFE function but seem unable to access the resolved value before I return from the function. In the snippet below i can print variable d to the console but i cant make it accessible outside the iffe and thus cannot return the result.

In the example below the first console.log returns the correct result but the second returns a pending promise. Any suggestions as to how to make this work or alternative methods will be much appreciated.

function getDNInfo (party){
  var result;
  result= (async () => { result = await mongo.findOne({DN:party.user_Number}, "BWUsers")
    .then(
            (d)=>{
              console.log(d)
              result=d;
            }"
        )}
   )();
   console.log(result)
   return result;

  }
  • 1
    You cannot synchronously work with a value retrieved in the future (asynchronously) – CertainPerformance Jun 13 '19 at 00:20
  • The `result` is returned before the callback has a chance to update the value. Are you expecting `getDNInfo` to be synchronous? – Jake Holzinger Jun 13 '19 at 00:28
  • I have read the duplicates referred to above- they dont answer my question explicitly. Every example i can find shows the value accessible within the promise but it is never shown accessible form outside the promise. It think the solution is to make the full call stack async functions, which I was trying to avoid but it seems there is no way around it. – Brendanone Jun 13 '19 at 05:16

2 Answers2

0

You should just be able to store the result from the query in a variable and return that variable like this:

async function getDNInfo(party) {
    var result = await mongo.findOne({DN:party.user_Number}, "BWUsers");
    return result;
}
RyanSurv
  • 46
  • 4
  • Thanks but making getDNInfo async just pushes the problem up the call stack. The function returns a pending promise. i need it to return the resolved value. – Brendanone Jun 13 '19 at 04:38
0

As Async function returns a promise so using Method 1 we can skip writing await as it will automatically wait for the query to get resolved without writing await Or you can always use Method 2 for traditional way of implementation.

Method 1:

 const getDNInfo = async (party) => {
        return mongo.findOne({DN:party.user_Number}, "BWUsers");
    }

Method 2:

    const getDNInfo = async (party) => {
                const result = await mongo.findOne({DN:party.user_Number}, "BWUsers");
                return result;
    }
Shumi Gupta
  • 1,505
  • 2
  • 19
  • 28
  • In both cases, an async function returns a promise so getDNInfo will be a pending promise rather than the resolved value. – Brendanone Jun 13 '19 at 05:14
  • I am not sure about how you want to use the result but if you will console.log(result) in Method 2 you will get the result. – Shumi Gupta Jun 13 '19 at 06:47