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
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:
- 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
await
keyword in its body
Due to #1, even synchronous functions return a Promise
:
Promise.all
Promise.all
is like a funnel that aggregates multiple Promise
s into one Promise
. If all sub-Promise
s are fulfilled, the funnel Promise
is considered fulfilled.