DEV Community

Discussion on: ⭐️🎀 JavaScript Visualized: Promises & Async/Await

Collapse
 
charanweb profile image
CHARAN

I got a difference answer when i tried the last code:
Async/await executing the next lines but saving in memory not showing in the output ,until await got the result. And its working synchronously. it shows first await result and executing line by line.


const x = Promise.resolve("Async function")

async function getme(){
 console.log("Before Async")
 const res = await x
 console.log(res)
 console.log("After Async")
}
getme()
//results
 Before Async
 Async function
 After Async
Promise {<fulfilled>: undefined}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
vitruvius21 profile image
Vitruvius • Edited

You place all console.logs in async function not outside, thus after "Before Async" it sees await, resolves promise and moves the getme() function into the microtasks, since there are no other tasks in callstack, getme() moves back to callstack and executes where it stopped i.e. at await, so res gets initialized, then 'Async function' and 'After Async' are logged.

Collapse
 
silverbullet069 profile image
VH • Edited

This is interesting, you use Promise.resolve function to return a Promise directly, instead of using a callback function that return that Promise.resolve function. This way, you have resolved your Promise right in line 1, not in line const res = await x.