- Published
Asynchronous Programming in JavaScript
- Authors
- Name
- Elif Nur Karakoç
JavaScript is considered a single-threaded language that can handle only one operation at a time. Synchronous processes wait for each to finish before moving on to the next. However, in web development, certain tasks take time to complete, like fetching data from an API, or waiting for user input. If these tasks were done one after the other, they would stop the main thread, causing the user interface to become unresponsive.
In JavaScript, asynchronous processes enable the program to keep running while waiting for tasks to finish, preventing block. This is often done using promises, async/await, or callbacks.
Synchronous/Asynchronous processes Here’s a brief example and explanation of each:
Callbacks
Callbacks in JavaScript are functions that are given as inputs to other functions and are executed once a particular task or event is completed.
Example:
// Step 1: Define the fetchData function that takes a callback
function fetchData(callback) {
// Simulate data fetching with a delay of 1000 milliseconds (1 second)
setTimeout(() => {
// Step 3: Invoke the callback with the data once the delay is over
callback("Data received");
}, 1000);
}
// Step 2: Define the displayData function that logs the received data
function displayData(data) {
console.log(data);
}
// Step 4: Call fetchData with displayData as the callback
fetchData(displayData);
After a second delay, you’ll see “Data received” logged to the console by the displayData function.
Promises:
In JavaScript, promises are objects that represent the eventual success or failure of an asynchronous task. Promises provide a cleaner approach compared to callbacks for handling asynchronous tasks, allowing us to link methods like .then() and .catch().
A Promise can be in one of three situations:
Pending: At the start, the promise is neither done nor unsuccessful. Fulfilled: The task succeeded, and the promise holds a result. Rejected: There was a problem during the task, and the promise has an explanation for the failure. Example:
// Step 1: Define the fetchData function that returns a Promise
function fetchData() {
return new Promise((resolve, reject) => {
// Step 2: Simulate data fetching with a delay of 1000 milliseconds (1 second)
setTimeout(() => {
// Step 3: Resolve the Promise with the data once the delay is over
resolve("Data received");
}, 1000);
});
}
// Step 4: Call fetchData, and use .then to handle the resolved data
fetchData().then(data => {
// Step 5: Log the received data to the console
console.log(data);
});
Async/Await:
In JavaScript, async is used for asynchronous functions that return promises, and await is used inside these functions to pause execution until promises are fulfilled, making code easier to understand.
Example:
// Step 1: Define a function that returns a promise
function fetchData() {
// Step 2: The promise resolves after a second delay
return new Promise((resolve, reject) => {
setTimeout(() => {
// Step 3: Resolve the promise with the message "Data received"
resolve("Data received");
}, 1000);
});
}
// Step 4: Declare an asynchronous function
async function displayData() {
// Step 5: Use the await keyword to wait for the fetchData promise to resolve
const data = await fetchData();
// Step 6: Log the resolved data to the console
console.log(data);
}
// Step 7: Call the asynchronous function to start the process
displayData();
In summary, using asynchronous programming in JavaScript is very helpful. It makes websites work faster and respond quickly to users. It also helps us handle tasks that take a long time in a smart way.