JavaScript is often used to make asynchronous functions calls from a web page to fetch data from another URL without refreshing page, form submission or redirecting it to a different URL. Typically, when you make asynchronous call the control returns back to your browser’s single JavaScript thread, and it continues executing other JavaScript code on your web page. The actual response is received only later when the backend processing is complete. For this purpose, we define a callback that is used to receive and handle the response of asynchronous call.
How to Return Response from Asynchronous Call in JavaScript
There are mainly 3 methods to return response from asynchronous call in JavaScript. We will make an asynchronous call to an API endpoint at example.com/api/endpoint and receive an image file in JSON format. We will use request library for making asynchronous calls since it is easy to use and popular.
1. Using Callback
// Callback method const request = require('request'); const url ='https://example.com/api/endpoint'; function callback(res, body) { console.log(JSON.parse(body)); } function getData(callback) { // Using the request module to request // data asynchronously request(url, (err, res, body) => { if (err) throw err; callback(res, body); }); } // Here we call the getData function // with the callback function getData(callback); console.log('asynchronous is awesome');
In the above code, we request API using getData function. We use request library to make the request to url, and assign a callback function that will be used later when we get response from URL. The request library basically requires 4 arguments – URL to be requested, err object for storing error related data, res object for response, body for storing response data. Within the callback, we also check if there is an error and throw it if that is the case. If there is no error, the callback function is called. We pass the res and body objects to callback, and simply print them. You can always do more processing with the body object which essentially contains the response data.
2. Using Then & Catch
In this case, we use promises to handle asynchronous call and its response. Here is a sample code for it.
const url ='https://example.com/api/endpoint'; const request = require('request'); // Promise with then catch const promise = new Promise((resolve, reject) => { request(url, (err, res, body) => { if (err) return reject(err); try { resolve(JSON.parse(body)); } catch(error) { reject(error); } }); }); promise.then((data) => { console.log(data); }) .catch((err)=>{ console.error(err); }); console.log('asynchronous is awesome');
Since request library does not return a promise, we explicitly assign a promise to handle the native response by wrapping the request inside a Promise constructor. The promise is then handled using .then() and .catch() methods. The advantage of this approach is that in case there are no errors, .then() will called and if there are any errors .catch() will be called. This separated error handling from response processing.
3. Using Async Functions with Await
In this example, we use asynchronous function that allow use to use synchronous programming constructs such as loops which cannot usually be used in asynchronous programming. Here is an example for it.
const url ='https://example.com/api/endpoint'; const request = require('request'); const getData = async () => { let data = await new Promise((resolve, reject) => { request(url, (err, res, body) => { if (err) return reject(err); try{ resolve(JSON.parse(body)); } catch(error) { reject(error); } }); }); try{ console.log(data); } catch(err){ console.error(err); } } getData(); console.log('asynchronous is best');
In this example, we define getData as an asynchronous function and wrap the response in Promise. Since promises take a while to process and respond, we use await keyword to wait for the promise to return a response. We have also used try…catch to process the data and catch an errors.
In this article, we have learnt how to return response from asynchronous call in JavaScript.
Also read:
How to Remove Key from JavaScript Object
How to Deep Clone Objects in JavaScript
How to Include JavaScript File in Another JavaScript File
How to Add Event to Dynamic Elements in JavaScript
How to Clone Objects in JavaScript
Related posts:
Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.