How does JavaScript handle asynchronous code

JavaScript handles asynchronous code using a combination of callbacks, promises, and async/await. This allows for non-blocking operations, enabling the execution of code while waiting for other processes to complete, such as fetching data from an API.

Initially, callbacks were the primary method for managing asynchronous operations. However, they can lead to "callback hell," making the code hard to read and maintain. To address this, promises were introduced, providing a more organized way of handling asynchronous tasks. Later, the async/await syntax was introduced to further simplify promise management, allowing developers to write asynchronous code that looks synchronous.

Example of Asynchronous Code Handling

// Example of using Promises function fetchData(url) { return new Promise((resolve, reject) => { setTimeout(() => { if (url) { resolve(`Data from ${url}`); } else { reject('No URL provided'); } }, 1000); }); } fetchData('https://api.example.com/data') .then(data => console.log(data)) .catch(error => console.error(error));

JavaScript Asynchronous Code Callbacks Promises Async/Await