Interview question
How would you predict the output order of a code snippet mixing sync code, setTimeout, and Promises? Sync code, setTimeout, और Promises mix करने वाले code का output order कैसे predict करें?
Answer
Predicting execution order requires classifying every line into one of three buckets: synchronous, microtask, or macrotask - then applying the priority rule: all sync first, then all microtasks, then one macrotask at a time.
console.log('1'); // SYNC
setTimeout(() => console.log('2'), 0); // MACROTASK
Promise.resolve().then(() => console.log('3')); // MICROTASK
console.log('4'); // SYNC
async function asyncFn() {
console.log('5'); // SYNC (runs immediately when asyncFn() is called)
await null;
console.log('6'); // MICROTASK (after the await)
}
asyncFn();
Promise.resolve().then(() => console.log('7')); // MICROTASK
console.log('8'); // SYNC
// STEP 1 - classify each log call:
// SYNC: 1, 4, 5, 8 (run immediately, in written order)
// MICROTASK (queued in order added): 3, 6, 7
// MACROTASK: 2
// STEP 2 - trace execution:
// All sync code runs top to bottom first: 1, 4, 5, 8
// (note: 5 runs synchronously because code BEFORE the first await in an
// async function executes immediately when the function is called)
// Then all microtasks drain in the order they were queued: 3, 6, 7
// Then the macrotask runs: 2
// FINAL OUTPUT: 1, 4, 5, 8, 3, 6, 7, 2
// General strategy for these interview questions:
// 1. Read top to bottom, noting each line's category (sync/micro/macro)
// 2. List sync lines in original order first
// 3. List microtask lines in the order they were SCHEDULED (not written)
// 4. List macrotask lines last, in the order their timers were scheduled
// (shorter delays generally run before longer ones)Execution order predict करने के लिए हर line को तीन categories में classify करना पड़ता है: synchronous, microtask, या macrotask - फिर priority rule apply करें: पहले सारा sync, फिर सारे microtasks, फिर एक-एक macrotask।
console.log('1'); // SYNC
setTimeout(() => console.log('2'), 0); // MACROTASK
Promise.resolve().then(() => console.log('3')); // MICROTASK
console.log('4'); // SYNC
async function asyncFn() {
console.log('5'); // SYNC (asyncFn() call होते ही चलता है)
await null;
console.log('6'); // MICROTASK (await के बाद)
}
asyncFn();
Promise.resolve().then(() => console.log('7')); // MICROTASK
console.log('8'); // SYNC
// STEP 1 - हर log call classify करें:
// SYNC: 1, 4, 5, 8
// MICROTASK: 3, 6, 7
// MACROTASK: 2
// STEP 2 - execution trace करें:
// पहले सारा sync code ऊपर से नीचे: 1, 4, 5, 8
// फिर microtasks उसी order में जिस order queue हुए: 3, 6, 7
// फिर macrotask: 2
// FINAL OUTPUT: 1, 4, 5, 8, 3, 6, 7, 2
// इन interview questions के लिए general strategy:
// 1. ऊपर से नीचे पढ़ें, हर line की category note करें
// 2. पहले sync lines original order में
// 3. फिर microtask lines schedule होने के order में
// 4. आखिर में macrotask lines, timer schedule होने के order मेंWas this answer clear?