Table of Contents
Overview:
Asynchronous programming is an essential part of JavaScript, but it can be challenging to handle the response from an asynchronous call. In this tutorial, we will look at three different solutions that can be used to handle the response from an asynchronous call in JavaScript: Promises with async/await, Callbacks, and Promises with then().
Promises with async/await (ES2017+)
Promises with async/await is the latest addition to the JavaScript language that allows us to write asynchronous code in a synchronous style. With the help of async and await keywords, we can write asynchronous code that is easier to read and understand.
Here’s an example of how to use Promises with async/await to handle an asynchronous call:
async function getData() {
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
const data = await response.json();
return data;
}
getData().then(data => console.log(data));
In the above example, we are using the fetch API to make an asynchronous call to the server to get some data. We are then using the await keyword to wait for the response and parse the JSON data. Finally, we return the data from the function and log it to the console.
Note that the function has been declared as async, and it always returns a Promise. The await keyword is used to wait for the Promise to resolve before continuing with the next line of code.
Callbacks
Callbacks are one of the most common ways to handle asynchronous code in JavaScript. A callback function is a function that is passed as an argument to another function and is executed when the asynchronous operation completes. Here’s an example of how to use callbacks to handle an asynchronous call:
function getData(callback) {
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/1');
xhr.onload = function() {
if (xhr.status === 200) {
callback(JSON.parse(xhr.responseText));
} else {
callback(null);
}
};
xhr.onerror = function() {
callback(null);
};
xhr.send();
}
getData(function(data) {
console.log(data);
});
In the above example, we are using the XMLHttpRequest object to make an asynchronous call to the server to get some data.
We are then passing a callback function as an argument to the getData() function. Once the asynchronous call is complete, the callback function is executed with the parsed JSON data as an argument.
Promises with then()
Promises with then() is another way to handle asynchronous code in JavaScript.
A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation and allows us to chain multiple asynchronous operations together. Here’s an example of how to use Promises with then() to handle an asynchronous call:
function getData() {
return new Promise(function(resolve, reject) {
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/1');
xhr.onload = function() {
if (xhr.status === 200) {
resolve(JSON.parse(xhr.responseText));
} else {
reject(Error(xhr.statusText));
}
};
xhr.onerror = function() {
reject(Error("Network Error"));
};
xhr.send();
});
}
getData().then(function(data) {
console.log(data);
}).catch(function(error) {
console.log(error);
});
In the above example, we are creating a new Promise that wraps the asynchronous call. The Promise is resolved with the parsed JSON data if the call is successful or rejected with an error message if the call fails.
We are then using the then() method to handle the resolved Promise and the catch() method to handle the rejected Promise. This way, we can ensure that our code executes properly even if an error occurs during the asynchronous call.
The then() method takes a callback function that is executed when the Promise is resolved. This function receives the resolved value as its argument. In our example, the resolved value is the parsed JSON data. We can then use this data in our code as needed.
The catch() method takes a callback function that is executed when the Promise is rejected. This function receives the error message as its argument.
In our example, the error message is a string that describes the error that occurred during the asynchronous call.
Overall, Promises are a powerful tool for handling asynchronous code in JavaScript. They allow us to write more readable and maintainable code by separating the code that initiates an asynchronous operation from the code that handles its result or error.