loading...

Discussion on: Asynchronous Javascript: 3 ways

Collapse
gilad profile image
Gilad Tsehori

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?

Collapse
wolverineks profile image
Kevin Sullivan

It blocks until the promise resolves

Collapse
tbutterwith profile image
Tom Butterwith Author

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:

const getPromise = () => Promise.resolve('My return value');
// the function is marked with the async keyword
const myFunction = async () => {  
  // tell the interpreter we want to wait on the response
  try {
    // start the asynchronous function
    const myPromise = getPromise();

    // Do some other work
    console.log("The function hasn't finished yet...");

    // Block execution till the promise has resolved
    const val = await myPromise;

    console.log(val); // prints 'My return value'
  } catch (error) {
    console.error(error.message);
  }
}


Collapse
dezfowler profile image
Derek Fowler

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.