17/11/2024
JavaScript runs in a single-threaded environment, meaning it can only perform one task at a time. However, many operations—like fetching data from a server or reading files—can take a long time and block the execution of other code. This is where asynchronous programming comes into play. It allows your JavaScript code to execute without waiting for these long-running operations, keeping your application smooth and responsive.
Callbacks are the simplest form of handling asynchronous operations. A callback function is executed after a certain task is completed. Here’s a simple example:
console.log("Start"); setTimeout(function() { console.log("This message is shown after 3 seconds."); }, 3000); console.log("End");
In this code:
setTimeout
function sets a timer for 3 seconds before executing the provided callback function.Start
End
This message is shown after 3 seconds.
While callbacks work, they can lead to “callback hell,” where nested callbacks make code difficult to read and maintain. Promises provide a more robust alternative. A promise represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
Here’s an example of using promises:
console.log("Start"); const myPromise = new Promise((resolve, reject) => { setTimeout(() => { resolve("This promise is resolved after 3 seconds."); }, 3000); }); myPromise.then((message) => { console.log(message); }); console.log("End");
In this example:
.then
method is used to specify what to do once the promise is resolved (log the message).Start
End
This promise is resolved after 3 seconds.
Async/await is syntactic sugar built on top of promises, making asynchronous code look and behave a bit more like synchronous code. You define a function as async
, and within it, you can use await
to pause execution until a promise resolves.
Here’s how it looks:
console.log("Start"); const myAsyncFunction = async () => { const myPromise = new Promise((resolve) => { setTimeout(() => { resolve("This promise is resolved after 3 seconds."); }, 3000); }); const message = await myPromise; // Waits for the promise to resolve console.log(message); }; myAsyncFunction(); // Call the async function console.log("End");
In this scenario:
await
keyword lets JavaScript know to wait for the promise to be resolved before continuing execution. However, it will not block other scripts.Start
End
This promise is resolved after 3 seconds.
With async/await, your asynchronous JavaScript code is cleaner and easier to read. You can handle errors more gracefully using try...catch
blocks:
const myAsyncFunction = async () => { try { const message = await myPromise; console.log(message); } catch (error) { console.error("An error occurred:", error); } };
Understanding asynchronous programming in JavaScript is crucial for building efficient web applications. By utilizing callbacks, promises, and async/await, you can create applications that are responsive and capable of handling lengthy operations without freezing the user interface.
17/11/2024 | VanillaJS
17/11/2024 | VanillaJS
18/11/2024 | VanillaJS
17/11/2024 | VanillaJS
29/10/2024 | VanillaJS
29/10/2024 | VanillaJS
17/11/2024 | VanillaJS