What is Promise in JavaScript?
A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. Promises provide a cleaner and more manageable way to handle asynchronous operations compared to callbacks, which can lead to "callback hell."
Example:
const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("Success"), 1000);
});
promise
.then(result => console.log(result)) // Success
.catch(error => console.log(error));
What is Event Loop in JavaScript?
Answer:
The event loop is a mechanism that allows
JavaScript to perform non-blocking I/O operations despite being
single-threaded. It continuously checks the call stack and the task
queue. When the call stack is empty, it pushes tasks from the queue to
the stack for execution.
Key components:
Call Stack: Tracks function calls.
Task Queue: Holds asynchronous callbacks (e.g.,
setTimeout
,Promise
).Microtask Queue: Holds higher-priority tasks like
Promise
resolutions.
Example
console.log("Start");
setTimeout(() => console.log("Timeout"), 0);
Promise.resolve().then(() => console.log("Promise"));
console.log("End");
// Output:
// Start
// End
// Promise
// Timeout