The Real Fullstack

The Async Trap

The log says “done” and the process exits. Why are the last records missing from the database?

مهندس9 دقيقةمحاكي الخط الزمنيتحدي الشيفرة
javascripttypescriptnode

لم يُترجم هذا التحدي إلى العربية بعد. أنت تقرأ النسخة الإنجليزية.

المهمة:First prove you can predict how the event loop orders synchronous code, microtasks and timers. Then choose an implementation where “done” really means done — within a 150 ms budget.السياق · أهداف التعلّم ▾

Quillfin's nightly import saves records with an async repository. In production, the job logs “done”, the container stops, and a few records are never written. Locally everything looks fine because the process keeps running a bit longer.

المهمة: First prove you can predict how the event loop orders synchronous code, microtasks and timers. Then choose an implementation where “done” really means done — within a 150 ms budget.

أهداف التعلّم

  • Order synchronous code, microtasks (promises, await) and tasks (timers).
  • Explain why forEach ignores async callbacks.
  • Choose between sequential and parallel awaiting.
المحاكاةمحاكاة
call stack
11. log("A")
22. log("F") (you: "B")
33. log("H") (you: "C")
microtasks
44. log("C") (you: "D")
55. log("E")
66. log("G") (you: "F")
77. log("D") (you: "G")
task queue
88. log("B") (you: "H")
تشغيل المحاكاة
console.log('A');setTimeout(() => console.log('B'), 0);Promise.resolve().then(() => console.log('C')).then(() => console.log('D'));queueMicrotask(() => console.log('E'));(async () => {  console.log('F');  await null;  console.log('G');})();console.log('H');
async function saveAll(items: Item[]) {  items.forEach(async (item) => { await repo.save(item); console.log('saved', item.id); });  console.log('done');                // forEach does not wait for async callbacks}

تبسيط

Saves are modelled as 100 ms timers. Real I/O callbacks run in other event-loop phases, but the microtask-before-task rule is the same. نموذج تعليمي — الأرقام توضّح سلوكًا وليست قياسات أداء.

المفاهيم

تحديات ذات صلة

المراجع