Advertisement
satishfrontenddev5

Untitled

Feb 18th, 2024
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # Promise and Illustration with Example:
  2. - **Promise**:
  3.   - A promise is an object representing the eventual completion or failure of an asynchronous operation.
  4.   - It allows handling asynchronous operations in a more manageable and readable way, avoiding callback hell.
  5. - **Example**:
  6.   ```javascript
  7.   const myPromise = new Promise((resolve, reject) => {
  8.     setTimeout(() => {
  9.       resolve("Promise resolved!"); // Success
  10.       // reject(new Error("Promise rejected!")); // Failure
  11.     }, 2000);
  12.   });
  13.  
  14.   myPromise
  15.     .then((result) => console.log(result)) // On success
  16.     .catch((error) => console.error(error)); // On failure
  17.   ```
  18.  
  19. # Closure and Lexical Environment with Working Example:
  20. - **Closure**:
  21.   - Closure is the combination of a function bundled together with references to its surrounding state (lexical environment).
  22.   - It allows a function to retain access to the variables of its containing scope even after the outer function has finished executing.
  23. - **Illustration**:
  24.   ```javascript
  25.   function outerFunction() {
  26.     const outerVariable = "I'm from outer function";
  27.     function innerFunction() {
  28.       console.log(outerVariable); // Inner function has access to outerVariable
  29.     }
  30.     return innerFunction;
  31.   }
  32.   const closureExample = outerFunction();
  33.   closureExample(); // Outputs: "I'm from outer function"
  34.   ```
  35.  
  36. # Node.js, Event Loop, Event Queues, and Types:
  37. - **Node.js**:
  38.   - Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. It allows executing JavaScript code outside the browser, such as on the server.
  39. - **Event Loop**:
  40.  - Event Loop is a core mechanism in Node.js responsible for handling asynchronous operations.
  41.  - It continuously checks the event queue for pending events and executes them one by one.
  42. - **Event Queues**:
  43.  - Node.js has several event queues:
  44.    1. **Timers Queue**: Contains callbacks from `setTimeout()` and `setInterval()`.
  45.    2. **I/O Queue**: Holds I/O-related callbacks like file system operations, network requests, etc.
  46.    3. **Microtask Queue (Job Queue)**: Contains promises' `then()` and `catch()` callbacks, `process.nextTick()`, and `queueMicrotask()`.
  47. - **Types of Event Queue**:
  48.   - **Macrotasks**: Represented by the Timers and I/O queues.
  49.   - **Microtasks**: Represented by the Microtask queue.
  50.   - Microtasks have higher priority and are executed before macrotasks in each iteration of the event loop.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement