0

Something escapes me about the result of using async / await

async function firstAsync() {
    let promise = new Promise((res, rej) => {
        setTimeout(() => res("Now it's done!"), 1000)
    });
    let result = await promise;
    console.log(result);
}
firstAsync();
console.log('toto')

The execution of the preceding example displays in the console:

toto

Now it's done!

This does not correspond at all to what should look like synchronous execution. In the case of synchronous execution the result should be

Now it's done!

toto

Did I miss something ?? Can someone explain to me what is going on?

phuzi
  • 12,078
  • 3
  • 26
  • 50
yvan Coyaud
  • 167
  • 1
  • 1
  • 10
  • You haven't done anything that would cause `console.log('toto')` to wait until after the promise returned from `firstAsync();` has settled before running. – Quentin Mar 12 '21 at 11:16
  • But it's _not_ synchronous. What makes you think it is? It's even in the name : `async function`. – Jeremy Thille Mar 12 '21 at 11:17
  • 1
    `async` functions are *asynchronous*. Your code isn't waiting for the asynchronous process started by `firstAsync` to complete before doing the `console.log('toto')`, so the `console.log('toto')` happens before code that waits for the process to complete happens. `async` functions return promises. To wait for the promise to settle before doing something, you have to consume that promise. For instance: `await firstAsync(); console.log('toto');` or in a context where you can't use `await`: `firstAync().then(() => { console.log('toto'); }).catch(error => { /*...handle/report error...*/ });` – T.J. Crowder Mar 12 '21 at 11:17
  • Try putting await in front of `firstAsync()`? – evolutionxbox Mar 12 '21 at 11:18
  • 1
    I wonder if there's a better dupetarget than the massive and very general [*"return the result of an asynchronous call"*](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) one... – T.J. Crowder Mar 12 '21 at 11:18
  • @T.J.Crowder https://stackoverflow.com/questions/41842147/javascript-sync-wait-for-async-operation-sleep or https://stackoverflow.com/questions/46515764/how-can-i-use-async-await-at-the-top-level maybe? – evolutionxbox Mar 12 '21 at 11:20
  • @T.J.Crowder perhaps I can suggest [this answer](https://stackoverflow.com/questions/66561573/what-guarantees-exist-in-asynchronous-javascript/66561926#66561926) that I wrote two days ago? – Jeremy Thille Mar 12 '21 at 11:20
  • @yvan Coyaud try `firstAsync().then(() => console.log('toto'))` Notice how using `aync/await` just moved the problem outward. I advise you to write your async code with `then` and later refactor with `async/await` when you have it working. Often times you will prefer the version using `then` – geoffrey Mar 12 '21 at 11:25

0 Answers0