0

I do not understand why the query variable has a value inside async function that changes when returned and declared in the global environment. I want to return the value from my database to a global variable outside of the async function. What is the logically reason this happens. How do I extract the integer value from the Promise {1}.

async function glob(){

    var result = await knex.raw('select max(glob) from or');
    let query = await result.rows[0].max ;
    console.log(query);
    return query ;
   
}

let go = glob();

setTimeout(()=>{console.log(go)},1000);
setTimeout(()=>{console.log(go == 1)},1000);

The console returns.

1
Promise { 1 }
false

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
JohnyClash
  • 630
  • 1
  • 5
  • 10
  • 1
    An `async` function will always return a Promise, you can either `await` the returned Promise in another `async` funcntion or use `.then(query => ...)` to obtain the query value. If you set `query` to a global variable, then you would need to ensure that the code tries to access it only does so after it has had its value set, which isn't an easy thing to do. So you're better off putting the code that relies on `query` in the `.then()` callback or after you have awaited the returned Promise – Nick Parsons Oct 09 '21 at 05:37
  • I believe that I have accessed the variable after the value has been set that is why I used setTimeouts, and that this is why it returns 1, the value I'm looking for is 1. I'm running this on a backend express server, is the best practice to wrap the entire entire express back end in an async function? – JohnyClash Oct 09 '21 at 13:06
  • You're logging the Promise in your setTimeout() that is returned by `glob()`, if you set a value to a global variable in your `glob` function and then log that in within your setTimeout() you would see it set, but that's not reliable, as your network request performed in glob isn't guaranteed be faster than your setTimeout delay. That's what callbacks/Promises `.then()` methods are used for, so you can run some code once the value becomes available. – Nick Parsons Oct 09 '21 at 13:16
  • It's not recommended to wrap your entire express backend in an `async` function, instead, you can use `.then()` or `await` the returned Promise in the parts of your code that need to use `query`. Depending on how your express server is set up / when you're running `glob()` and what parts will need to use `query`, it may be ok to use a global variable (which would need to be set within `glob()` and not returned if you wish to do that) but it's hard to tell if that's what you need without more context. – Nick Parsons Oct 09 '21 at 13:19

0 Answers0