Understanding Promises
Mike Sherov
Promise.resolve('Principal').then(role => console.log(`${role} Engineer`));
Core UX @ Skillshare
What is a Promise?
Promises are future values!
or a future reason that the value couldn't be gotten!
Why Promises?
- Avoids Callback hell
- Allows Composition of async operations
- Creates a building block for
futureasync syntax abstractions - Provides a unified way of dealing with transaction timing
- callback: a function to be executed (event handlers)
- async: code that executes in a future call stack! (or between call stacks!?!?!)
- Settled vs. Pending:
- settled: async operation has completed
- pending: async operation has not completed
- Resolved vs. Rejected:
- Resolved (fulfilled): completely successfully
- Rejected: completed unsuccessfully
Some Jargon
- via constructor with "executor" callback
- via Promise.resolve
- via Promise.reject
- anything you return/throw in an async function
- anything you return/throw in a "then" function
Creating a promise
- .catch ... this is just sugar for .then(null, errorCallback)
- .then(successCallback, errorCallback)
- will call successCallback when promise resolves, or immediately (but still async) if the promise is already resolved
- will call errorCallback when promise rejects, or immediately (but still async) if the promise is already rejected
using a promise (basic)
- successCallback receives as it's first argument the resolved value
- errorCallback receive as it's first argument the rejected reason
using a promise (values & reasons)
- a resolved promise can be turned into a rejected one if...
- you return a new rejected Promise in successCallback
- you throw in a successCallback
- a rejected promise can be turned into a resolved one if...
- you don't throw in a errorCallback
- you don't return a rejected Promise in errorCallback
using a promise (values and reasons)
- REMEMBER: .then returns a new promise, with a new resolved value (or rejected reason) for future .thens!
- can avoid this changing what you're chaining off of!
- if you return a Promise from within .then, the return value of .then is the inner promise's value! tricky
using a promise (chaining)
- Promise.all: takes in an array of Promises (or values), and will return a resolved promise whose value is an array of the resolved values of the passed in promises if they all resolve, otherwise returns a rejected promise with the reason set to the reason the first promise rejected
- Promise.race: takes in an array of Promises (or values), and will return a resolved promise whose value is the value of the first promise that resolves, or reject with the first promise that rejects
Promise.all & Promise.race
Understanding Promises
By mikesherov
Understanding Promises
- 1,953