DEV Community

Discussion on: I just don't understand async/await 😢!

Collapse
 
paxfeline profile image
David Newberry • Edited

Mozilla has very good documentation. I always consult it.

developer.mozilla.org/en-US/docs/W...

A function marked as async will happen concurrently with other code. So for example, here's some very slightly altered code from the MDN documentation:


function resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved');
    }, 2000);
  });
}

async function asyncCall() {
  console.log('calling');
  var result = await resolveAfter2Seconds();
  console.log(result);
  // expected output: 'resolved'
}

asyncCall();

console.log( "after async call" );

If you run that, what you'll see output is:

calling
after async call

and a couple seconds later

resolved

The MDN documentation explains that only async functions are allowed to use the "await" keyword. This causes the function's execution to pause and wait for some Promise to be fulfilled. This isn't allowed in normal functions because it would 'lock up' the execution of javascript code.