Asynchronous JavaScript- Callbacks, Promises, and Async/Await
JavaScript is a most widely used programming language mostly used in making dynamic websites. Asynchronous processes, such as making API calls, reading files, or carrying out difficult tasks, is an essential component of modern web applications. The three widely used methods for managing asynchronous actions in JavaScript are – callbacks, promises, and async/await. In this article, we will be learning all the asynchronous method step by step.
1. What are Callbacks in Javascript?
A callback is a function that receives an argument from another function and is then performed later, once an asynchronous task has been completed. To ensure a seamless user experience, it enables us to handle asynchronous actions without pausing the main program.
for Example:
function fetchData(url, callback) { // Simulate an asynchronous operation (e.g., an API call) setTimeout(() => { const data = { name: "John", age: 30 }; callback(data); }, 1000); } function processData(data) { console.log(`Name: ${data.name}, Age: ${data.age}`); } fetchData("https://example.com/api/data", processData);
The fetchData function performs an API call with a one-second delay and sends the received data to the specified callback function.The name and age properties of the received data are logged by the processData function, which acts as the callback.To ensure a seamless user experience, callbacks are used to keep the main application running while the asynchronous operation is finished.
2. What is Promises in Javascript?
To solve the problems caused by callback hell, promises were added in ECMAScript 6 (ES6). A promise stands for a benefit that might not be available right away but will be fulfilled or rejected in the future. The code is easier to manage since it offers a more organized way to handle asynchronous processes.
Resolve and Reject are the two parameters required by the promise function. Reject is used when a mistake is made, but resolve is used when a success is achieved.

Do you want to learn HTML to React? 🔥
If yes, then here is our Master HTML to React 📚 In this eBook, you’ll Get Complete Free Hand Written Notes on HTML, CSS, JavaScript, and React 💪. It includes 450 Projects with source code. and 250+ Most Asked Interview Questions
Get your eBook now! 👇
function fetchData(url) { return new Promise((resolve, reject) => { // Simulate an asynchronous operation (e.g., an API call) setTimeout(() => { const data = { name: "John", age: 30 }; resolve(data); // Promise resolved with data // If an error occurs, use reject(error) }, 1000); }); } fetchData("https://example.com/api/data") .then((data) => { console.log(`Name: ${data.name}, Age: ${data.age}`); }) .catch((error) => { console.error("Error fetching data:", error); });
The fetchData function returns a new Promise that simulates an API call with a one-second delay. If it is successful, it fulfills the promise and returns a data object named “John” with an age of “30”. The reject method can be used to deal with an error that arises during the process.
The Promise is returned after executing fetchData(“https://example.com/api/data”), enabling us to handle the resolved data using the.then() method. In this instance, we record the name and age attributes of the data object to the console. The catch() method, which logs an error message, can be used to manage any errors that may arise during the operation.
3. What is Async and Await in Javascript?
Async/await is a syntactical feature in JavaScript that provides a more synchronous-like way of handling asynchronous operations. Promises are used to simplify the process of working with asynchronous code.
Async function:
An async function is a type of javascript function that allows us to use the await keyword. When you define a function with the async keyword, it automatically returns a promise. This promise will resolve with the value returned by the async function or reject with an error thrown inside the function.
Await Keyword:
Await keyword is used inside an async function. It is used to pause the execution of the async function until the promise is resolved or rejected. When await is used with a promise, it waits for the promise to get completely (resolve or reject) and then returns the resolved value or throws an error if the promise is rejected.
function fetchData(url) { return new Promise((resolve, reject) => { // Simulate an asynchronous operation (e.g., an API call) setTimeout(() => { const data = { name: "John", age: 30 }; resolve(data); // Promise resolved with data // If an error occurs, use reject(error) }, 1000); }); } async function processData() { try { const data = await fetchData("https://example.com/api/data"); console.log(`Name: ${data.name}, Age: ${data.age}`); } catch (error) { console.error("Error fetching data:", error); } } processData();
The fetchData function generates a Promise that resolves with a data object containing the name and age after a 1-second wait. We can use await inside the processData method because it is defined with the async keyword.
As soon as the Promise delivered by fetchData is resolved, the processData function pauses using await fetchData(“https://example.com/api/data”). The data is then allocated to the data variable, and the name and age attributes are then recorded to the console.
We can write asynchronous code more simply and linearly using async/await, which makes it easier to comprehend and maintain, especially when working with numerous asynchronous activities. It makes managing Promises easier and does away with the requirement for explicit.chains of then() and.catch()
Modern JavaScript development involves dealing with asynchronous operations on frequently. Async/Await and Promises offer better organized and readable alternatives to the traditional way of handling asynchronous processes, which was callbacks. Async/Await builds on Promises to deliver even cleaner, synchronous-like code while helping to avoid callback irrationality Developers can choose how to handle asynchronous actions in their JavaScript applications more wisely by understanding these strategies.
If you find out this Blog helpful, then make sure to search Codewithrandom on Google for Front End Projects with Source codes and make sure to Follow the Code with Random Instagram page.
Follow: CodewithRandom
Author: Arun