How to Return the Response from an Asynchronous Call in JavaScript

Here are three ways to return the response from an Asynchronous Call in JavaScript.

  1. Promises with async/await (ES2017+)
  2. Promises with then() (ES2015+)
  3. 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

Promises with async:await(ES2017+)

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

Promises with then() (ES2015+)

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

Callback function

That’s it.

Leave a Comment