Async Programming - 13% Flashcards
Promise
An obj representing the eventual completion or failure of an async operation and its resulting value.
Promise creation
Use the new keyword, and pass resolve and reject.
Most often we consume already-created promises from APIs, rarely make our own.
ex:
Const promise1 = new Promise((resolve, reject) => { …}
Returns a Promise obj w/ 2 internal properties - state and result.
Promise states
Pending, Fulfilled, Rejected
Fulfilled if resolved w/value.
Rejected if rejected w/error.
(resolved and settled are not states)
other Promise descriptors (not states)
Resolved - cannot be resolved or rejected b/c it has either already been fulfilled or rejected OR it has been ‘locked in’ to follow another promise.
Settled - no longer pending - has been fulfilled or rejected.
possible actions after a Promise is settled
.then, .catch, .finally
.finally - runs when it settles (either fulfills or rejects)
Can use to stop a loading indicator before .then / .catch
Has no arguments, the res or err passes through to next action.
Adding an action to a settled Promise will occur after the stack has been emptied (like setTimeout with 0 ms)
Promise Concurrency
Not true concurrency, but control switches making it appear they are running at once.
Syntax ex: Promise.all(<iteratable>)</iteratable>
.all - fulfills when ALL fulfill, rejects when ANY reject
.allSettled - fulfills when ALL are settled
.any - fulfills when ANY fulfill, rejects when ALL reject
.race - fulfills when ANY fulfill, rejects when ANY reject
Async Programming
Using the async keyword allows for the fn to contain await expressions, which make promise-returning fs behave like synchronous code.
The return of an async fn behaves like it is wrapped in a Promise.resolve, except the async return is a reference.