When an async
function hits the first await
in the function, it immediately suspends further execution of that function and then immediately returns a promise from the function. The caller receives that promise and continues to execute. So, the current function is suspended, but not the caller or the rest of the JS engine.
So, in your code:
const get=async ()=>{
const y=await "hello"
console.log(y)
}
console.log("start")
get()
console.log("end")
Here's the sequence of events:
- Logs "start"
- Starts to execute
get()
- Gets to the first
await
- Suspends further execution of the
get()
function
- Returns promise from
get()
- Calling code continues to execute and logs "end"
- When calling code returns back to the event loop, the
await
finishes because there was no actual promise there to wait for and the get()
function resumes executing and it logs "hello"
So, await
only suspends execution of the current function, causing it to immediately return a promise and the calling code then continues to execute. Sometime later when the statement you are awaiting resolves (usually a promise) and the interpreter has returned back to the event loop, then the function will continue its execution until either the next await
or until it gets to its return value which then becomes the resolved value of the promise it originally returned and that promise gets resolved (which your code was ignoring).
Note, await
should generally be used with promises, not with constants. Though it doesn't cause an error to await
something that isn't a promise, it doesn't do anything useful.