Skip to content

Reading 09

Avrey125 edited this page Sep 19, 2019 · 1 revision

Promise API

There are 5 static methods in the Promise class.

EX. let promise = Promise.all([...promises...]);

Promise.all: Promise.all takes an array of promises (technically can be any iterable, but usually an array) and returns a new promise. The new promise resolves when all listed promises are settled and the array of their results becomes its result.

the order of resulting array members is the same as source promises.

EX. Promise.all([ new Promise(resolve => setTimeout(() => resolve(1), 3000)), // 1 new Promise(resolve => setTimeout(() => resolve(2), 2000)), // 2 new Promise(resolve => setTimeout(() => resolve(3), 1000)) // 3 ]).then(alert); // 1,2,3 when promises are ready: each promise contributes an array member

Promise.all rejects as a whole if any promise rejects.

Polyfill

used if browser doesnt support promise.all

EX. if(!Promise.allSettled) { Promise.allSettled = function(promises) { return Promise.all(promises.map(p => Promise.resolve(p).then(value => ({ state: 'fulfilled', value }), reason => ({ state: 'rejected', reason })))); }; }

Promise.race: Similar to Promise.all, but waits only for the first settled promise, and gets its result

EX. let promise = Promise.race(iterable);

Promise.resolve(value) – makes a resolved promise with the given value.

Promise.reject(error) – makes a rejected promise with the given error.

Clone this wiki locally