2026-01-05 01:34
Status: #baby
Tags: #javascript
Promise.all
In Javascript, when handling async logic, sometimes you need to wait for multiple promises to resolve in your code. One of the ways to handle code execution after multiple promises have resolved is using the built in Promise.all method like so.
Let's imagine you have a chat messaging platform, the user experience will go something like this:
- User Logs In
- Fetch User Messages
- Display User Messages to Front-End
Once I was working for a company where a bug fix request came in, users were experiencing vastly different login load page times, with some users reporting 30 second loading screen wait times!
As I dove into the issue, I noticed something off with the message load logic, it looked something like this:
async function fetchMessagesSequentially(messageIds) {
const messages = [];
for (const id of messageIds) {
const response = await fetch(`/api/messages/${id}`
const message = await response.json();
messages.push(message);
}
return messages;
}
Here's the problem, while this function will successfully fetch our messages from the back-end, it's fetching them sequentially, meaning one after the other. Since it takes time for the data of each message to travel back and forth between the server and client, the latency stacked up, the more messages a user had, the longer their load times!
const myvar = 11;
I solved the bug by refactoring the sequential message retrieval to fetch them in parellel using Promise.all
async function fetchMessagesConcurrently(messageIds) {
const promises = messageIds.map(id => fetch(`/api/messages/${id}`)
.then(res => res.json()));
return Promise.all(promises);
}
Promise.all is a method that receives an itterable of promises as an argument, and executes promises concurrently, so rather than them waiting one after the other, they can all begin execution at the same time. Now instead of the user load time being load time x number of messages, the load time will only take as long as the longest single request. It reduced page load times from 30 seconds to 1.5 for the worst affected user.
References
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
Linked Citations