All Interview Questions
About Lesson

Q10.  How are asynchronous operations handled in JS and what is the difference between different queues like micro and macro task queues?

Ans:
Asynchronous code in JavaScript is handled using a combination of the event loop, callback queue, microtask queue, and APIs provided by the JavaScript runtime environment (such as the browser or Node.js). Here is a detailed explanation of how async code is handled in JavaScript:

1. Event Loop

The event loop is a fundamental part of the JavaScript runtime that manages the execution of multiple pieces of code over time, handling both synchronous and asynchronous tasks. It allows JavaScript to be non-blocking and single-threaded, making it possible to execute asynchronous code without halting the execution of the main program.

2. Callback Queue (or Task Queue)

The callback queue holds tasks (or callbacks) that are ready to be executed after the currently executing script finishes. These tasks include:

  • Timers (e.g., setTimeout, setInterval)
  • Event handlers (e.g., user input, DOM events)
  • I/O operations (e.g., reading files, network requests)

3. Microtask Queue

The microtask queue holds microtasks, which are typically smaller tasks that should be executed immediately after the currently executing script but before any tasks in the callback queue. Microtasks include:

  • Promises (.then, .catch, .finally handlers)
  • MutationObserver callbacks
  • queueMicrotask

4. Web APIs and Node.js APIs

These APIs provide asynchronous functionality:

  • Web APIs: Include setTimeout, setInterval, AJAX (e.g., XMLHttpRequest, fetch), DOM events, etc.
  • Node.js APIs: Include fs module for file system operations, http module for network requests, etc.

How Asynchronous Code Execution Works

  1. Invocation: When an asynchronous operation (e.g., a timer, a network request) is initiated, the JavaScript engine delegates it to the appropriate API provided by the runtime environment.
  2. Execution: The JavaScript engine continues executing other code (synchronously) without waiting for the asynchronous operation to complete.
  3. Completion: Once the asynchronous operation completes, the runtime environment (e.g., the browser) places the corresponding callback or promise resolution/rejection handler into the callback queue or microtask queue.
  4. Event Loop:
    • The event loop checks if the call stack is empty. If it is, it first processes all microtasks in the microtask queue.
    • After processing all microtasks, it processes one task from the callback queue.
    • This cycle repeats, ensuring that the JavaScript engine continues to execute any pending tasks or microtasks.

Example: Async Code with Promises

console.log(“Start”);

setTimeout(() => {
  console.log(“Timeout callback”);
}, 0);

Promise.resolve()
  .then(() => {
    console.log(“Promise callback”);
  });

console.log(“End”);
Execution Steps:
    1. Synchronous Code: The engine executes console.log(“Start”) and console.log(“End”) immediately.
    2. Async Operation (Timer): setTimeout callback is registered with a delay of 0 milliseconds. This callback is placed in the callback queue after the delay.
    3. Async Operation (Promise): Promise.resolve() creates a resolved promise. The .then handler (console.log(“Promise callback”)) is placed in the microtask queue.
  • Event Loop:
    • The call stack becomes empty after console.log(“End”).
    • The event loop processes the microtask queue first, executing console.log(“Promise callback”).
    • Then, the event loop processes the callback queue, executing the setTimeout callback (console.log(“Timeout callback”)).
Start
End
Promise callback
Timeout callback

Q11: Implement Promise.all Problem Description :Let’s implement our own version of Promise.all(), a promiseAll function, with the difference being the function takes in an array instead of an iterable. Be sure to read the description carefully and implement accordingly

Usage:
    // Resolved example.
    const p0 = Promise.resolve(3);
const p1 = 42;
const p2 = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve(“foo”);
    }, 100);
});
await promiseAll([p0, p1, p2]); // [3, 42, ‘foo’]
// Rejection example.
const p0 = Promise.resolve(30);
const p1 = new Promise((resolve, reject) => {
    setTimeout(() => {
        reject(“An error occurred!”);
    }, 100);
});
try {
    await promiseAll([p0, p1]);
} catch (err) {
    console.log(err); // ‘An error occurred!’
}
Ans:
async function promiseAll(promises) {
    const results = [];
    for (const promise of promises) {
        try {
            results.push(await promise);
        } catch (error) {
            throw error;
        }
    }
    return results;
}

© GeekySanjay