Here are three ways to return the response from an Asynchronous Call in JavaScript.
- Promises with async/await (ES2017+)
- Promises with then() (ES2015+)
- Callback function
Method 1: Promises with async/await (ES2017+)
The ECMAScript version released in 2017 introduced syntax-level support for asynchronous functions. With the help of async and await, you can write asynchronous code in a “synchronous style”.
// Using 'superagent' which will return a promise.
let superagent = require('superagent')
async function getAllData() {
try {
let users = await superagent.get('https://jsonplaceholder.typicode.com/users');
return users
} catch (error) {
return null;
}
}
(async function () {
let info = await getAllData();
console.log(info._body);
})()
Output
Install the “superagent” library using the “npm install superagent –save” command.
Method 2: Promises with then() (ES2015+)
Promises are containers for future values. When the promise receives the value (it is resolved) or when it is canceled (rejected), it notifies all of its “listeners” who want to access this value.
let superagent = require('superagent')
function getAllData() {
return superagent.get('https://jsonplaceholder.typicode.com/users')
.then(users => {
return users;
})
.catch(error => {
return null;
});
}
getAllData()
.then(info => {
console.log(info.body);
})
.catch(error => {
console.log('Error:', error);
});
Output
Method 3: Callback function
A callback is a function that is passed to another function. In the context of an asynchronous process, the callback will be called once the asynchronous process is done. The result is typically passed to the callback.
let superagent = require('superagent')
function getAllData(callback) {
superagent.get('https://jsonplaceholder.typicode.com/users')
.end((err, res) => {
if (err) {
callback(null, err);
} else {
callback(res, null);
}
});
}
getAllData((result, error) => {
if (error) {
console.log('Error:', error);
} else {
console.log(result.body);
}
});
Output
That’s it.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.