Muhammad Fari Madyan
Hire me
Node.js & TS · part 2 of 13

Node.js & TypeScript Backend Part 2: Async and Promises — Promise.all vs allSettled, Limiting Parallelism & Unhandled Rejections

Part two of a Node.js & TypeScript series that opens with a quiz: Promise.all is fail-fast but does not cancel, allSettled for partial results, limiting parallelism so the database pool is not flooded (login waits 1,024 ms vs 21 ms), return await inside try, forEach that does not wait, and unhandled rejections.

Muhammad Fari Madyan

· 11 min read

Baca dalam Bahasa Indonesia →

Opening: A Small Feature, a Slow Login

Picture a simple feature: a Resend tickets to every attendee button. The code is three lines and looks tidy:

JS
const attendees = await getAllAttendees(eventId);   // 500 people
await Promise.all(attendees.map((a) => resendTicket(a)));

It passes review. It passes the tests. Then in production, every time someone presses that button, people who are logging in wait a full second. Nothing shows up in the error logs.

There is nothing wrong with Promise.all. What is wrong is how we use it. In this part we fix the four things that most often make async code behave strangely.


Warm-Up Quiz: Do You Still Remember?

Answer before you run the code. All correct? Jump to the Summary. Missed one? Let's refresh the material.

The code uses Indonesian names, because this series is written in both languages: tunggu (wait), ambil (get), saldo (balance), kirim (send), hasil (result), gagal (failed), simpan (save), selesai (done).

Question 1. ambilSaldo fails after 100 ms. kirimEmail takes 300 ms. What gets printed?

JS
const tunggu = (ms) => new Promise((r) => setTimeout(r, ms));

async function ambilProfil() { await tunggu(50); return 'profil'; }
async function ambilSaldo() { await tunggu(100); throw new Error('saldo timeout'); }
async function kirimEmail() { await tunggu(300); console.log('email tetap terkirim'); return 'email'; }

try {
  const hasil = await Promise.all([ambilProfil(), ambilSaldo(), kirimEmail()]);
  console.log(hasil);
} catch (err) {
  console.log('gagal:', err.message);
}
  • A. Only gagal: saldo timeout. The email is cancelled.
  • B. gagal: saldo timeout, then email tetap terkirim (the email was still sent).
  • C. [ 'profil', undefined, 'email' ]
Show the answer to question 1

B. Promise.all rejects as soon as one fails, but it does not cancel the others. kirimEmail has been running since the start, so it still finishes. Nobody is waiting for its result, that is all.

Question 2. simpanPesanan (save order) always throws. Does the catch below catch it?

JS
async function bayar() {
  try {
    return simpanPesanan();        // note: no await
  } catch (err) {
    return 'ditangani: ' + err.message;
  }
}
  • A. Yes, the catch catches it
  • B. No, the error escapes to whoever called bayar()
Show the answer to question 2

B. Without await, bayar (pay) returns the Promise from simpanPesanan straight away and leaves the try block. By the time that Promise rejects, the try/catch is long gone.

Question 3. What prints first?

JS
async function simpan(id) { await tunggu(50); console.log('tersimpan', id); }

[1, 2, 3].forEach(async (id) => { await simpan(id); });
console.log('selesai?');
  • A. tersimpan 1, tersimpan 2, tersimpan 3, selesai?
  • B. selesai?, then tersimpan 1, 2, 3
Show the answer to question 3

B. forEach knows nothing about Promises. It calls our function three times, throws away the Promises it gets back, and finishes. Nothing waits.

Question 4. On Node.js 22, a Promise rejects with no await and no .catch. What happens?

  • A. A yellow warning appears and the app keeps running
  • B. The process stops with exit code 1
Show the answer to question 4

B. Since Node.js 15, an unhandled rejection stops the process, just like an uncaught exception.

Question 5. The database connection pool has 10 connections. We run 500 queries at once with Promise.all. Five milliseconds later, another user logs in and needs one query. What happens to them?

  • A. They are served right away, because it is a different query
  • B. They wait behind hundreds of those queries
Show the answer to question 5

B. The pool only has 10 connections. 490 other queries are already queued, and the login query joins at the very back. Section 4 has the numbers.

What did you score? Let's take them apart.


1. A Promise Is an Order Receipt

When you order a coffee, the cashier gives you a receipt. There is no coffee yet, but the receipt promises you will get one of two things: the coffee, or the news that they are out of milk.

A Promise is exactly that. Its states:

  • pending: still being made,
  • fulfilled: it worked, and there is a value,
  • rejected: it failed, and there is an error.

await means "I will stand at the counter until this receipt is done". While you stand, the thread does not. As in Part 1, the cook keeps serving other orders.

The important part people forget: the order starts being made when the receipt is printed, not when you await it. That is the key to question 1.


2. Promise.all: All or Nothing

JS
const [profile, permissions] = await Promise.all([getProfile(userId), getPermissions(userId)]);

Promise.all fits when every result is required. The dashboard needs the profile and the permissions. If either fails, the page really cannot be shown.

Two things to remember about it:

  1. Fail-fast: as soon as one Promise rejects, Promise.all rejects with that first error. Results that already succeeded are thrown away.
  2. No cancellation: the other Promises keep running to the end. The output of question 1:
TEXT
gagal: saldo timeout
email tetap terkirim

If those leftover Promises write to the database or send email, the effect still happens even though the request was already answered with "failed". If you need real cancellation, the operation has to accept an AbortSignal, for example fetch(url, { signal }).


3. Promise.allSettled: Report Everything

JS
const hasil = await Promise.allSettled([ambilProfil(), ambilSaldo()]);
console.log(hasil);
const gagal = hasil.filter((h) => h.status === 'rejected');
console.log(`${gagal.length} dari ${hasil.length} gagal`);
TEXT
[
  { status: 'fulfilled', value: 'profil' },
  {
    status: 'rejected',
    reason: Error: saldo timeout
        at ambilSaldo (...)
  }
]
1 dari 2 gagal

(The last line reads "1 of 2 failed".) allSettled never rejects. It waits for everything to finish and gives you a report per item. It fits when partial results are still useful:

  • send a notification to 50 attendees, then record who failed so you can retry,
  • a dashboard with several boxes, where one failing box must not leave the page empty.
Promise.allPromise.allSettled
One failsRejects at onceStill waits for all
ResultAn array of valuesAn array of { status, value } or { status, reason }
Use it whenEvery result is requiredPartial results are still useful

Two relatives: Promise.race (whichever settles first, success or failure) and Promise.any (the first one that succeeds). For timeouts, AbortSignal.timeout(3000) is usually cleaner than race, because the operation actually stops.


4. Limit Parallelism: Don't Flood the Database

Back to question 5. This simulates a pool like pg.Pool: at most 10 connections, the rest queue up. We run 500 queries (20 ms each), and 5 ms later a user logs in:

JS
const tunggu = (ms) => new Promise((r) => setTimeout(r, ms));

// A fake pool like pg.Pool: at most 10 connections, the rest queue (FIFO).
function buatPool(max) {
  let dipakai = 0;
  const antrean = [];
  const ambil = () => new Promise((resolve) => {
    if (dipakai < max) { dipakai++; resolve(); } else antrean.push(resolve);
  });
  const lepas = () => {
    const berikut = antrean.shift();
    if (berikut) berikut(); else dipakai--;
  };
  return {
    async query(ms = 20) {
      await ambil();
      try { await tunggu(ms); } finally { lepas(); }
    },
  };
}

(dipakai = in use, antrean = queue, ambil = take, lepas = release.) The result:

TEXT
Promise.all  : login menunggu 1024 ms
limit 5      : login menunggu 21 ms

A database pool with 10 connections: Promise.all pushes 500 queries in so the login query queues at the back and waits 1,024 ms, while a limit of 5 concurrent queries leaves room so login waits only 21 ms

Click the diagram to see it full size.

With Promise.all, all 500 queries land in the pool's queue at once. The login query is number 501. The total work is the same, but someone else pays for it.

The fix: cap how many run at the same time. Here is a small version you can copy:

JS
async function mapWithLimit(items, limit, fn) {
  const results = new Array(items.length);
  let next = 0;
  async function worker() {
    while (next < items.length) {
      const i = next++;                // safe: there is only one JavaScript thread
      results[i] = await fn(items[i], i);
    }
  }
  const workerCount = Math.min(limit, items.length);
  await Promise.all(Array.from({ length: workerCount }, worker));
  return results;
}

// usage
await mapWithLimit(attendees, 5, (a) => resendTicket(a));

Five "workers" take items one at a time from the same list. next++ is safe without a lock because, as in Part 1, there is only one JavaScript thread. The results stay in the same order as the input.

A few notes:

  • Pick a limit below the pool size, so there is always a free connection for other requests.
  • In a real project, a small library such as p-limit does the same thing.
  • If there are thousands of items and the user does not need to wait for the result, that is a sign the work belongs in a queue (see Part 1, section 6).

5. try/catch with await

return await inside try

Here is question 2 with its output:

JS
async function bayarTanpaAwait() {
  try {
    return simpanPesanan();        // no await
  } catch (err) {
    return 'ditangani: ' + err.message;
  }
}

async function bayarDenganAwait() {
  try {
    return await simpanPesanan();  // with await
  } catch (err) {
    return 'ditangani: ' + err.message;
  }
}
TEXT
ditangani: DB mati
lolos dari catch: DB mati

(ditangani = handled, lolos dari catch = escaped the catch, DB mati = DB is down.) The rule is simple: inside try, always return await. Outside try, a plain return is fine.

forEach does not wait

Question 3 has two fixes, depending on what you need:

JS
for (const id of [1, 2, 3]) {
  await simpan(id);              // one by one, in order
}
await Promise.all([4, 5, 6].map((id) => simpan(id))); // at the same time, but awaited
console.log('selesai!');

Use for...of when order matters or you want to stop when one fails. Use map + Promise.all (or mapWithLimit) when they can run together. The same goes for filter, some and reduce: they do not wait for Promises.


6. Unhandled Rejections: A Promise That Fails with No Witness

JS
async function catatLog() {
  throw new Error('log server mati');
}

catatLog(); // called with no await and no .catch
setTimeout(() => console.log('masih hidup?'), 100);
TEXT
Error: log server mati
    at catatLog (.../unhandled.js:2:9)
    ...
exit code: 1

masih hidup? (still alive?) never prints. Every other request running in that process is cut off too.

If you really do want "fire and forget", still attach a .catch:

JS
void catatLog().catch((err) => logger.warn({ err }, 'failed to send the log'));

Then, as a last safety net, add a global handler. Its job is to log and shut down cleanly, not to swallow the error:

JS
process.on('unhandledRejection', (reason) => {
  console.error('unhandledRejection:', reason instanceof Error ? reason.message : reason);
  process.exitCode = 1;
  process.kill(process.pid, 'SIGTERM'); // let the clean shutdown path do its work
});

Why stop instead of carrying on? After an unexpected error, we no longer know whether the app's state is still correct. It is safer to stop, finish the requests in flight, and let the platform start a fresh process. How to stop cleanly is Part 4.


Summary

  • A Promise starts running when it is created, not when it is awaited.
  • Promise.all: everything must succeed. Fail-fast, but it does not cancel the rest.
  • Promise.allSettled: partial results are still useful. It never rejects.
  • Cap parallelism below the pool size. 500 queries at once made login wait 1 second. With a limit of 5, it was 21 ms.
  • Inside try, use return await. forEach does not wait. Use for...of or map + Promise.all.
  • An unhandled rejection kills the process. Add .catch to fire-and-forget calls, and a global handler that logs and then shuts down cleanly.

Closing & What's Next

The Resend tickets button from the opening needs a one-line change: Promise.all becomes mapWithLimit(attendees, 5, ...). Sending takes a little longer, and nobody waits at login anymore.

So far we have talked about one process. In the next part we start many processes at once, and see why a rate limit that works perfectly in one process suddenly lets 20 requests through instead of 5.

Grab your coffee, see you in the next part!

ShareLinkedInXWhatsApp

Written by Muhammad Fari Madyan

Senior Backend Engineer and co-founder of LampungDev. I write up what I build so others can learn from it.

Work with me
← part 1The Event Looppart 3 →Stateless Scaling

Muhammad Fari Madyan

Senior Backend Engineer building real-time, high-concurrency systems that hold up in production. Co-founder of LampungDev. Based in Bandar Lampung, Indonesia (UTC+7), working remote.

Work

Case studiesCahTixExam platform, 4 stacksOpen source

© 2026 Muhammad Fari Madyan

Designed and built by Muhammad Fari Madyan