loading...

Discussion on: Asynchronous Javascript: 3 ways

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);
  }
}