JavaScript Async/Await Explained in 10 Minutes

10 minutes to learn JavaScript Async/Await

Previously we used callback.

Then we used promises.

Now we use Async/Await.

1, What is Async/Await?

Async – Define Async function someName(){… })

  • Automatically converts the function to a Promise
  • When an asynchronous function is called, the return value of the function is resolved
  • Asynchronous functions can be used internallyawait

Await – suspend execution of asynchronous functions (var result = Await someAsyncCall();)

  • When used in front of Promise,awaitWait for the Promise to complete and return the result of the Promise
  • await onlyUsed with Promise,Can’tUsed with callback
  • awaitCan only be used inasyncIn the function

2, whether Async/Await will replace Promise

Don’t.

  • Underlying Async/Await still uses Promise.
  • This function is required when multiple asynchronous functions are executed simultaneouslyPromise.all
async function getABC() {
  let A = await getValueA(); // getValueA takes 2 seconds
  let B = await getValueB(); // getValueA takes 4 seconds
  let C = await getValueC(); // getValueA takes 3 seconds

  return A*B*C;
}Copy the code

Each time the await keyword is encountered, the Promise will stop until the end of the run, so the total cost is 2+4+3 = 9 seconds. Await changes asynchrony to synchronization.

async function getABC() {
  // promise.all () allows all asynchronous functions to be executed simultaneously
  let results = await Promise.all([ getValueA, getValueB, getValueC ]); 

  return results.reduce((total,value) = > total * value);
}Copy the code

The total time of the function is 4 seconds (the time of getValueB).

3, Async/Await error handling

In Async/Await syntax, we can use try/catch for error handling. The.catch() branch in the Promise goes into the catch statement.


JavaScript Async/Await Explained in 10 Minutes

Discuss address: 10 minutes to learn JavaScript Async/Await

If you’d like to participate in the discussion, click here