In the last example, after the await keyword: does the program continue executing until the variable val is required (and waited upon) or does it "block" there?
That is, if there is something between the await and the console.log(val), will it be executed immediately or only once the promise is resolved?
Hi. Yes it's a blocking call. If you want to start the asynchronous function, do some other work, then wait for the return instead you can go with something like this:
constgetPromise=()=>Promise.resolve('My return value');// the function is marked with the async keywordconstmyFunction=async()=>{// tell the interpreter we want to wait on the responsetry{// start the asynchronous functionconstmyPromise=getPromise();// Do some other workconsole.log("The function hasn't finished yet...");// Block execution till the promise has resolvedconstval=awaitmyPromise;console.log(val);// prints 'My return value'}catch(error){console.error(error.message);}}
await isn't blocking, it creates a continuation from all the code within the async function that appears after the await statement. That continuation runs when the thing being awaited resolves.
An async function implicitly returns a promise when it hits the first await statement and control is returned to the calling code which will continue to run.
If there was a return value from myFunction, that is also wrapped in a promise and you'd need to use an await or a .then() to use it.
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.
In the last example, after the await keyword: does the program continue executing until the variable val is required (and waited upon) or does it "block" there?
That is, if there is something between the await and the console.log(val), will it be executed immediately or only once the promise is resolved?
It blocks until the promise resolves
Hi. Yes it's a blocking call. If you want to start the asynchronous function, do some other work, then wait for the return instead you can go with something like this:
await isn't blocking, it creates a continuation from all the code within the async function that appears after the await statement. That continuation runs when the thing being awaited resolves.
An async function implicitly returns a promise when it hits the first await statement and control is returned to the calling code which will continue to run.
If there was a return value from myFunction, that is also wrapped in a promise and you'd need to use an await or a .then() to use it.