In JavaScript, What Is The Method To Retrieve The Response From An Asynchronous Call?

In JavaScript, you cannot directly return the response from an asynchronous call as it does not block the execution of your code. However, you can utilize promises or callback functions to retrieve the result of an asynchronous call.

Using Promises:

function getData() {
  return new Promise((resolve, reject) => {
    // Asynchronous operation, such as making an API request
    // Simulating an API request using setTimeout
    setTimeout(() => {
      const data = 'Response from asynchronous call';
      resolve(data); // Resolve the promise with the retrieved data
    }, 2000);
  });
}

getData()
  .then(response => {
    console.log(response); // Output: Response from asynchronous call
  })
  .catch(error => {
    console.error(error);
  });

Using Callbacks:

function getData(callback) {
  // Asynchronous operation, such as making an API request
  // Simulating an API request using setTimeout
  setTimeout(() => {
    const data = 'Response from asynchronous call';
    callback(data); // Pass the retrieved data to the callback function
  }, 2000);
}

getData(response => {
  console.log(response); // Output: Response from asynchronous call
});

Both approaches work by providing a function (either resolve in promises or the callback function) to be executed when the asynchronous operation is complete.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!