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}
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.
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.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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 ,untilawait
got the result. And its working synchronously. it shows firstawait
result and executing line by line.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.
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.