JavaScript async and await

up:: JavaScript

related:

Promise

Promise is a JavaScript object that represent a value in the future. It has two values:

  1. state
  2. error or value

Any function that returns a Promise is an asynchronous function.

  • The Promise is returned synchronously, and can be accessed immediately
  • The value is asynchronous and can only be accessed after the Promise has settled.

State

The state of a Promise can be one of three values:

  1. Pending: Initial state
  2. Fulfilled: Completed sucessfully
  3. Rejected: Failed

async

The async keyword adds a special functionality to a function:

  1. It always return a Promise
  2. It can use the await keyword in its body

Due to #1, even synchronous functions return a Promise:

async function getFive(num) {
	return 5;
}
console.log(getFive()); // Promise { … }

Promise.all

Promise.all is like a funnel that aggregates multiple Promises into one Promise. If all sub-Promises are fulfilled, the funnel Promise is considered fulfilled.