Asynchronous JavaScript
JavaScript is a single-threaded language, which means it can only execute one task at a time.
That's where asynchronous programming comes in. It allows us to perform multiple tasks at the same time without blocking the main thread.
Let's explore the different ways of writing asynchronous code in JavaScript.
Callbacks
A callback function is a function that is passed as an argument to another function and is executed after the first function completes its task.
Callbacks are commonly used in asynchronous operations like fetching data from an API or handling user events.
As an example:
function fetchData(url, callback) {
const xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onload = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
callback(xhr.responseText);
}
};
xhr.send();
}
fetchData("https://jsonplaceholder.typicode.com/posts/1", function (data) {
console.log(data);
});
In this example:
- The
fetchData
function sends an HTTP request to a URL and retrieves the data. - It takes a callback function as an argument, which is executed when the data is returned.
- The
console.log
statement is called inside the callback function, after the data is retrieved.
Promises
A promise is an object that represents a value that may not be available yet, but will be resolved in the future.
Promises are used to handle asynchronous operations that return a single value.
As an example:
function fetchData(url) {
return new Promise(function (resolve, reject) {
const xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onload = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
resolve(xhr.responseText);
} else {
reject(xhr.statusText);
}
};
xhr.onerror = function () {
reject(xhr.statusText);
};
xhr.send();
});
}
fetchData("https://jsonplaceholder.typicode.com/posts/1")
.then(function (data) {
console.log(data);
})
.catch(function (error) {
console.error(error);
});
In this example:
- The
fetchData
function returns a promise that resolves with the data when it is retrieved, or rejects with an error message if there was an error. - The then method is called on the returned promise to handle the resolved value, while the catch method is called to handle any errors.
Async/await
Async/await is a more recent addition to JavaScript and is a way to write asynchronous code that looks more like synchronous code. It allows developers to write asynchronous code that looks like synchronous code, making it easier to read and understand.
As an example:
async function fetchData(url) {
try {
const response = await fetch(url);
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
fetchData("https://jsonplaceholder.typicode.com/posts/1");
In this example:
- The
fetchData
function is marked asasync
, which allows us to use theawait
keyword inside it. - The
await
keyword is used to wait for a promise to resolve before continuing to the next line of code. - The
try...catch
block is used to handle any errors that may occur while fetching the data.