Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 7 of 10 · Promises and Async/Await
Interview question

What is a microtask and how do Promises relate to the event loop? Microtask क्या है और Promises event loop से कैसे संबंधित हैं?

Answer

Promise callbacks (.then, .catch, .finally, and code after await) are queued as microtasks, which run after the current synchronous code finishes but before the next macrotask (like setTimeout).

console.log('1: Sync start');

setTimeout(() => console.log('2: Macrotask (setTimeout)'), 0);

Promise.resolve().then(() => console.log('3: Microtask (Promise)'));

console.log('4: Sync end');

// Output order:
// 1: Sync start
// 4: Sync end
// 3: Microtask (Promise)
// 2: Macrotask (setTimeout)

// Explanation: All synchronous code runs first.
// Then ALL queued microtasks run before the next macrotask.
// Even setTimeout(fn, 0) waits behind every pending microtask.
Event loop priority:
1. Run all synchronous code (call stack) → 2. Drain the entire microtask queue (Promises, queueMicrotask) → 3. Run one macrotask (setTimeout, setInterval, I/O) → 4. Repeat from step 2
// Nested microtasks also run before macrotasks
setTimeout(() => console.log('macrotask'), 0);
Promise.resolve()
    .then(() => console.log('microtask 1'))
    .then(() => console.log('microtask 2'));
// Output: microtask 1, microtask 2, macrotask

Promise callbacks (.then, .catch, .finally, await के बाद का code) microtasks के रूप में queue होते हैं, जो current synchronous code के बाद पर अगले macrotask (जैसे setTimeout) से पहले चलते हैं।

console.log('1: Sync start');

setTimeout(() => console.log('2: Macrotask'), 0);

Promise.resolve().then(() => console.log('3: Microtask'));

console.log('4: Sync end');

// Output:
// 1: Sync start
// 4: Sync end
// 3: Microtask
// 2: Macrotask
Event loop priority:
1. सारा synchronous code चलता है → 2. पूरी microtask queue drain होती है → 3. एक macrotask चलता है → 4. फिर से step 2 से

Was this answer clear?