Asynchronous JavaScript is a programming approach that enables the non-blocking execution of tasks, allowing concurrent operations, improved responsiveness, and efficient handling of time-consuming operations in web applications, JavaScript is a single-threaded and synchronous language. The code is executed in order one at a time, But Javascript may appear to be asynchronous in some situations.
There are several methods that can be used to perform asynchronous javascript tasks, which are listed below:
Approach 1: Using callback
Callbacks are functions passed as arguments to be executed after an asynchronous operation completes. They are used in asynchronous JavaScript to handle responses and ensure non-blocking execution,
Syntax:
function myFunction(param1, param2, callback) {
// Do some work...
// Call the callback function
callback(result);
}
Example: In this example, the myFunction simulates an async task with a 3s delay. It passes fetched data to the callback, which logs it. Output after 3s:
JavaScript function myFunction(callback) { setTimeout(() => { const data = { name: "Aman", age: 21 }; callback(data); }, 3000); } myFunction((data) => { console.log("Data:", data); });
Output:
Data: { name: 'Aman', age: 21 }
Approach 2: Using Promises
Promises are objects representing the eventual completion (or failure) of an asynchronous operation, providing better handling of asynchronous code with .then() and .catch().
Syntax:
let promise = new Promise(function(resolve, reject){
//do something
});
Example: In this example, The function mydata() returns a Promise that resolves with data after a delay. The data is logged, or an error is caught if rejected, after 2 seconds.
JavaScript function mydata() { return new Promise((resolve, reject) => { setTimeout(() => { const data = { name: "Rohit", age: 23 }; resolve(data); }, 2000); }); } mydata() .then((data) => { console.log("Data:", data); }) .catch((error) => { console.error("Error:", error); });
Output:
Data: { name: 'Rohit', age: 23 }
Similar Reads
JavaScript - How Does Asynchronous Code Work? Asynchronous code in JavaScript allows to execute code in the background without blocking the main thread. Asynchronous JavaScript is mainly used for handling tasks like network requests, file operations, and API calls. To understand how asynchronous code works, it's important to first know the conc
4 min read
Synchronous and Asynchronous in JavaScript JavaScript is known for its ability to handle both synchronous and asynchronous operations. Understanding how these two things work is important for writing efficient, responsive, and user-friendly applications. In this article, we will see the differences between synchronous and asynchronous JavaSc
4 min read
Explain Asynchronous vs Deferred JavaScript Generally, when we use a script tag to load any JavaScript code, the HTML parsing is paused by the browser when it encounters the script tag and it starts to download the JavaScript file first. The HTML elements script tag will not be executed until the browser is done with downloading the script an
3 min read
JavaScript Callbacks In JavaScript, callbacks play an essential role in handling asynchronous tasks like reading files, making API requests, and executing code after certain events. If youâve ever heard the phrase "I will call back later!", thatâs exactly how callbacks work.What is a Callback Function?A callback functio
4 min read
How to chain asynchronous functions in JavaScript ? JavaScript is a single-threaded, asynchronous programming language. Thus, some time-consuming operations like I/O, accessing the database, network calls, etc. are performed asynchronously so that it does not interrupt things in the only JS thread. This can be done by asynchronous code like promises
2 min read