23
loading...
This website collects cookies to deliver better user experience
async/await
and try/catch pattern
or with thePromise.all()
method. This blog article is about the latter one.Promise.all(iterable)
iterable
- An iterable object such as an Array.Promise.all()
method takes an iterable of promises as an input (commonly an array), and returns a single Promise that resolves to an array of the results of the input promises.Promise.all
method needs an iterable as an input, an array with promises and it will behave as a single Promise. So we can add a .then
handler to handle the returned Promise, which will receive the result of the resolved Promises. To catch and handle potential errors a catch
handler should be attached as well.const all = Promise.all([
new Promise((resolve, reject) =>
setTimeout(() => resolve(1), 1000),
),
new Promise((resolve, reject) =>
setTimeout(() => resolve(2), 2000),
),
new Promise((resolve, reject) =>
setTimeout(() => resolve(3), 3000),
),
]).catch(err => console.log('Promise was rejected!', err));
all.then(results => console.log(results)); // the output is: [1, 2, 3]
mkdir node-promise-all
npm init -y
to be able to install node packages.cd node-organize
npm init -y
node-fetch
to make fetch requests.npm install node-fetch
index.js
file.touch index.js
// import node-fetch
const fetch = require('node-fetch');
// set url as constant
const URL = 'https://jsonplaceholder.typicode.com/todos';
const ids = [1, 2, 3, 4, 5];
// create a request for each todo id and decode as json.
// json() returns a Promise
const getTodo = id =>
fetch(`${URL}/${id}`).then(response => response.json());
// Map over the ids, returning a promise for each one.
const arrayOfPromises = ids.map(id => getTodo(id));
// create a single Promise for all the Promises
Promise.all(arrayOfPromises)
.then(todos => todos.map(todo => todo.title))
.then(titles => console.log(titles)) // logs titles from all the todos
.catch(err => console.log(err));
Promise.all
in a case where some Promises reject, we need to make the Promise.all utility fault tolerant.const promises = [
fetch(url),
fetch(url),
Promise.reject(new Error('This fails!')),
fetch(url),
];
const allPromisesWithErrorHandler = promises.map(promise =>
promise.catch(error => error),
);
Promise.all(allPromisesWithErrorHandler).then(results => {
// we get results even if a promise returns rejected!
// But results can be a mix of errors and success values.
console.log(results);
});
Promise.all
is useful to make several asynchronous calls and collect all their results together.Promise.all
waits for all fulfillments (or the first rejection).Promise.all
helps us to write cleaner and maintainable code.