Introduction
Asynchronous JavaScript allows JavaScript code to be executed in a non-blocking manner, meaning it does not have to wait for each operation to complete before moving on to the next one. This is particularly useful for tasks that take a significant amount of time or depend on external resources, such as fetching data from a server or reading from a file.
Let's look at a few key techniques for writing asynchronous JavaScript.
setTimeout
Refer to the following code snippet.
123456789console.log("Start");
setTimeout(function() {
console.log("Inside setTimeout");
}, 3000);
console.log("End");
In this example, setTimeout is an asynchronous function. It waits 3000 milliseconds (3 seconds) before executing the function that logs "Inside setTimeout". But while setTimeout is waiting, the rest of the code continues to run, so "End" is logged before "Inside setTimeout".
Callbacks
A callback is a function passed into another function as an argument. The callback function can then be executed at a later time. This is one of the simplest ways to handle asynchronous operations.
Refer to the following code snippet.
1234567891011function fetchData(callback) {
setTimeout(function() {
console.log("Data fetched");
callback();
}, 2000);
}
fetchData(function() {
console.log("Callback function executed");
});
In this example, the fetchData function takes a callback function as an argument and calls it after it logs "Data fetched".
Promise
A Promise is an object representing the eventual completion or failure of an asynchronous operation. It returns a value that is either a resolved value or a reason why it rejected. Promises are more powerful and flexible than callbacks and form the basis of modern asynchronous JavaScript.
Refer to the following code snippet.
12345678910let promise = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('Data fetched!');
}, 2000);
});
promise.then(function(data) {
console.log(data); // 'Data fetched!' after 2 seconds
});
Async/Await
This is a syntactic feature introduced in ES2017 that makes working with Promises much easier and more readable. It allows you to write asynchronous code that looks and behaves like synchronous code.
Refer to the following code snippet.
12345678async function fetchAndLogData() {
let response = await fetch('https://api.example.com/data');
let data = await response.json();
console.log(data);
}
fetchAndLogData();
Note
Note that the fetch
API returns a Promise, which is why we can use await
with it. The await
keyword can only be used inside an async
function. It causes the async function to pause and wait for the Promise to resolve or reject, and then resumes the execution of the async function and returns the resolved value. If the Promise rejects, it throws an error, which can be caught using a try/catch
block.
These techniques help make JavaScript more flexible and allow for more efficient execution of code, particularly in situations where you are dealing with operations that could take an unpredictable amount of time, such as network requests.