JavaScript async and await
up:: JavaScript
related:
Promise
Promise is a JavaScript object that represent a value in the future.
It has two values:
- state
- error or value
Any function that returns a Promise is an asynchronous function.
- The
Promiseis returned synchronously, and can be accessed immediately - The value is asynchronous and can only be accessed after the
Promisehas settled.
State
The state of a Promise can be one of three values:
- Pending: Initial state
- Fulfilled: Completed sucessfully
- Rejected: Failed
async
The async keyword adds a special functionality to a function:
- It always return a
Promise - It can use the
awaitkeyword 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.