1. Promises
let promise = new Promise((resolve, reject) => {let isSuccess = true; // Simulate success/failureif (isSuccess) {resolve("Success!");} else {reject("Failure!");}});promise.then((message) => {console.log(message); // Output: Success!}).catch((error) => {console.error(error);});(code-box)
Chaining Promises:
Promise chaining is a JavaScript technique in which multiple promises are performed sequentially. Each promise in the chain is triggered by the resolution of the previous promise, allowing a series of asynchronous operations to be executed sequentially.
let promise = new Promise((resolve, reject) => {resolve(1);});promise.then((value) => {console.log(value); // Output: 1return value * 2;}).then((value) => {console.log(value); // Output: 2return value * 3;}).then((value) => {console.log(value); // Output: 6});(code-box)
2. Async/Await
Async Await in javascript allow you to write asynchronous code that appears synchronous. An async function always returns a promise, and await i.e pauses the function's execution until the promise is resolved.
Basic Async/Await Example:
async function fetchData() {
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("Data fetched!"), 2000);
});
let result = await promise; // Wait until the promise resolves
console.log(result); // Output: Data fetched!
}
fetchData();(code-box)
async function fetchData() {let promise = new Promise((resolve, reject) => {setTimeout(() => reject("Error fetching data!"), 2000);});try {let result = await promise;console.log(result);} catch (error) {console.error(error); // Output: Error fetching data!}}fetchData();(code-box)
3. Callbacks
Callbacks in javascript are functions that are supplied as arguments to other functions and then performed once the operation is completed.Prior to promises and async/await, this was the typical way to handle asynchronous operations..
Basic Callback Example:
function fetchData(callback) {
setTimeout(() => {
callback("Data fetched!");
}, 2000);
}
fetchData((message) => {
console.log(message); // Output: Data fetched!
});(code-box)
Let me explain you with how we handle errors using callbacks
function fetchData(callback) {setTimeout(() => {const error = true;if (error) {callback("Error fetching data!", null);} else {callback(null, "Data fetched!");}}, 2000);}fetchData((error, data) => {if (error) {console.error(error); // Output: Error fetching data!} else {console.log(data);}});(code-box)
4. Event Loop
The event loop in JavaScript is a key feature that controls the execution of various pieces of code across time. It enables JavaScript to perform non-blocking operations by delegating tasks to the system whenever possible.
console.log("Start");setTimeout(() => {console.log("Timeout"); // Executed last}, 0);Promise.resolve().then(() => {console.log("Promise"); // Executed before setTimeout});console.log("End");(code-box)
StartEndPromiseTimeout(code-box)
In this example, setTimeout
is pushed to the event loop, while the Promise
is handled by the microtask queue, which is processed before the macrotask queue (setTimeout
).
Summary
- Promises: Used for handling asynchronous operations with
.then
and.catch
. - Async/Await: Syntactic sugar over promises, making asynchronous code look synchronous.
- Callbacks: Functions passed as arguments to other functions, executed after an asynchronous operation completes.
- Event Loop: Manages execution of code, events, and tasks in JavaScript.
These concepts form the core of asynchronous JavaScript and are essential for building efficient and responsive web applications.