Promises Flashcards
1
Q
promises
A
- object that represents the outcome of an asynchronous call
- consists of a status and a value
- value gets updated when async call is completed
2
Q
promises
states
A
3 states
- pending
- fulfilled (resolved)
- rejected
- a promise that is fulfilled or rejected is said to be settled
- a settled promise cannot be unsettled
- a settled promise has a value associated with it, which cannot change
3
Q
promises
Promise constructor
A
- used to create the promise object
- constructor is where all the async logic takes place
- promise object will automatically be rejected if error is raised anywhere in constructor
- constructor takes a function which take two parameters, resolve and reject
- resolve and reject are built-in functions that will update promie’s status and value
- the parameter of resolve will be passed to promise’s success handler
- the parameter of reject will be passed to the promise’s failure handler
Syntax
var myPromise = new Promise( function(resolve, reject) { // Async logic resolve("Some value"); //-and/or- reject("Error object or value"); });
4
Q
promises
then
A
- built-in method used to handle success and failure
- then method takes two functions as parameters: success callback and failure callback
- the success callback receive parameter that was passed to resolve (in constructor)
- failure callback receives parameter that was passed to reject (in constructor)
- both are optional
- then always returns another promise
- this makes them chainable
- user can also return a promise himself
- if user returns value (or error) instead, new promise will automatically be fulfilled (or rejected) with that value (or error)
- a promise can be ‘thenned’ more than once (can handle success/failure on same promise multiple times
- a use then on a promise even after it is settled (overcomes race condition)
Syntax
promise.then(function success(result) {} }, function failure(err) { });
5
Q
promises
catch
A
- built-in function available to promise objects
- returns another promise (like then)
- can be used to handle errors that arose anyway along promise chain
- syntactc sugar; equivalent to then’s failure handler [.then(undefined, failure())]
- considered good practice to end all promises with catch
6
Q
Promise.all
A
- built-in method on Promise constructor
- takes an array (or iterable) of promises
- returns a promise that resolves when all promises resolve
- or rejects when first promise rejects
- value of resolve promise is array of values from indiviudal promises
- value of reject promise is the value of first promise to reject
7
Q
Promise.race
A
- built-in method on Promise constructor
- takes an array (or iterable) of promises
- returns a single promise that resolves when first promise resolves
- or rejects when first promise rejects
- value is value of promise that resolved or rejected first