Promise API
Opened this issue · 0 comments
jeanpan commented
Promise.resolve
let promise = Promise.resolve(value);
Returns a resolved promise with the given value
.
Same as
let promise = new Promise(resolve => resolve(value));
The method is used when we already have a value, but would like to have it "wrapped" into a promise.
Example.
function loadCached(url) {
let cache = loadCached.cache || (loadCached.cache = new Map());
if (cache.has(url)) {
return Promise.resolve(cache.get(url)); // (*)
}
return fetch(url)
.then(response => response.text())
.then(text => {
cache.set(url,text);
return text;
});
}
Promise.reject
let promise = Promise.reject(error);
Same as
let promise = new Promise((resolve, reject) => reject(error));
Promise.all
We want to run many promises to execute in parallel, and wait till all of them are ready.
let promise = Promise.all([...promises...]);
It takes an array of promises (technically can be any iterable, but usually an array) and returns a new promise.
let names = ['iliakan', 'remy', 'jeresig'];
let requests = names.map(name => fetch(`https://api.github.com/users/${name}`));
Promise.all(requests)
.then(responses => {
// all responses are ready, we can show HTTP status codes
for(let response of responses) {
alert(`${response.url}: ${response.status}`); // shows 200 for every url
}
return responses;
})
// map array of responses into array of response.json() to read their content
.then(responses => Promise.all(responses.map(r => r.json())))
// all JSON answers are parsed: "users" is the array of them
.then(users => users.forEach(user => alert(user.name)));
If any of the promises is rejected, Promise.all
immediately rejects with that error.
Promise.race
Similar to Promise.all
, it takes an iterable of promises, but instead of waiting for all of them to finish, it waits for the first result (or error), and goes on with it.
Promise.race([
new Promise((resolve, reject) => setTimeout(() => resolve(1), 1000)),
new Promise((resolve, reject) => setTimeout(() => reject(new Error("Whoops!")), 2000)),
new Promise((resolve, reject) => setTimeout(() => resolve(3), 3000))
]).then(alert); // 1