So you have a bunch of Promises, and you want to proceed only when all of them are resolved. In JavaScript there are 2 main approaches to solving this.
Let’s start with 3 Promises:
const users = getUsers();
const articles = getArticles();
const likes = getLikes();
And a simple message that we’d like to print out to the screen when all promises are resolved.
console.log(`${users.length} users have created ${articles.length} articles and placed ${likes.length} likes`);
The problem is that if we try to run this code without any modifications, we’ll get undefined
messages instead of the actual results that our get
functions return.
undefined users have created undefined articles and placed undefined likes
Async/await
The first approach might be to put everything into an async
function and add await
keywords to wait until the promises are resolved:
const users = await getUsers();
const articles = await getArticles();
const likes = await getLikes();
It solves our problem, but introduces another one. Now, we’re waiting for the promises to resolve one-by-one which is far from optimal as the functions getUsers
, getArticles
and getLikes
don’t depend on each other.
Promise.all
Fortunately, JavaScript has a very handy function called Promise.all
.
It works very intuitively by accepting an array of Promises and returning an array of resolved values.
The biggest benefit of Promise.all is that we process all the promises at once and don’t have to wait for the sequential processing.
const data = await Promise.all([getUsers(), getArticles(), getLikes()];
The results will be stored in the data
array and accessible as data[0]
, data[1]
and data[2]
.
And our console.log
will render something like this:
50 users have created 120 articles and placed 34 likes
Improvements
Then, we can further improve the code by destructuring the array and giving proper names to our variables:
const [users, articles, likes] = await Promise.all([getUsers(), getArticles(), getLikes()];
console.log(`${users.length} users have created ${articles.length} articles and placed ${likes.length} likes`);
Read more JavaScript tutorials or Learn Full-Stack JS from scratch!