What are the ways to make the code Asynchronous?
Ways to Make Code Asynchronous in JavaScript
Asynchronous programming is essential in JavaScript for handling time-consuming tasks like fetching data from servers, reading files, or executing long-running computations without blocking the main thread. Here are some common ways to achieve asynchrony in JavaScript:
a . Callbacks:
b .promises:
c .Async/Await:
Callbacks: Callbacks are one of the oldest and most common ways to handle asynchronous operations in JavaScript. A callback is a function passed as an argument to another function, which will be invoked later, usually when the asynchronous task completes.
function read(callback) { setTimeout(() => { const data = 'Some asynchronously data'; callback(data); }, 1000); } read((data) => { console.log(data); }); /* The read function simulates an asynchronous operation using setTimeout, then invokes the provided callback function with data after a 1-second delay. The code demonstrates asynchronous programming and the callback pattern commonly used in JavaScript for handling non-blocking operations.*/
Promises: Promises provide a cleaner and more structured way to deal with asynchronous code compared to callbacks. A Promise represents a value (or the eventual completion or failure of an asynchronous operation) and allows chaining multiple asynchronous operations together.
function fetchData() { return new Promise((resolve, reject) => { setTimeout(() => { const data = 'Some asynchronously data'; resolve(data); }, 1000); }); } fetchData() .then((data) => console.log(data)) .catch((error) => console.error(error)); // This code utilizes Promises to handle asynchronous operations, with the fetchData function resolving after a delay and then logging the data, or catching and logging any errors that may occur during execution.
Async/Await: Async functions and the await keyword provide a more synchronous-looking syntax for writing asynchronous code. An async function returns a Promise, and the await keyword can be used to pause execution until the Promise is resolved or rejected.
async function fetchData() { return new Promise((resolve, reject) => { // Simulate fetching data from a server setTimeout(() => { const data = 'Some data fetched asynchronously'; resolve(data); }, 1000); }); } async function getData() { try { const data = await fetchData(); console.log(data); } catch (error) { console.error(error); } } getData();