How to return the response from an asynchronous call in Javascript?

In this article, we will take a look at:

An asynchronous call in JavaScript can return a response in multiple ways. First, let’s understand the problem. Let’s say you have a function called foo, which is asynchronous and will provide the data after some time. This can be done in one of two ways. It can accept a callback, which it will call when it is ready with the data. It can also promise to return.

The set Timeout function, for example, accepts callbacks and executes them after a specified time. Let’s assume you choose the first option. Then you can pass it to the set Timeout function.

Example

function myFunc(cb) {
   setTimeout(() => cb(100), 1000);
}
myFunc((a) => console.log(a))

Output

100

This will invoke the set Timeout function, with a callback that will be executed after 1000 ms. It will execute the function and call the passed callback (CB), with the value from set Timeout’s callback.

Using Promises

This can also be done using promises. Wrap the async function in a promise, and then resolve it with the function’s return. To use the return value from the async functions, you can use the chain-the-then method and pass it to a callback.

Example

new Promise(resolve => setTimeout(() => resolve(100), 1000))
   .then(console.log)

Output

100