The other day, I was working on an API in Node.js + MongoDB.
I had to:
- Check if a user exists
- Get all their successful payment records
The normal way?
const user = await User.findOne({ email: userEmail });
const payments = await Payment.find({ user: userEmail, status.successful });
This runs one after another. Slow. 😴
Then I remembered something simple but powerful which is Promise.all().
const [user, successfulPayments] = await Promise.all([
User.findOne({ email: userEmail }),
Payment.find({ user: userEmail, status.successful })
]);
Now both queries run at the same time.
If one takes 150ms and the other 200ms → my API returns in 200ms instead of 350ms.
💡 When to use Promise.all()
✅ When your async tasks don’t depend on each other
✅ When you want to save time by running them in parallel
⚠ If one fails, they all fail — so always handle errors
try {
const [user, successfulPayments] = await Promise.all([
User.findOne({ email: userEmail }),
Payment.find({ user: userEmail, status: status.successful })
]);
console.log("=================> User email", successfulPayments)
} catch (error) {
console.error(error);
}
Sometimes performance boosts don’t come from complex algorithms
they come from knowing the right tool at the right time.
Do you use Promise.all() in your APIs? Or are you still running things one after another?
Top comments (0)