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

Table of Contents

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

 

How Lack of Rest Can Impact Your Finances Small Businesses Can Enhance File Management Following these Tips How Much Do Real Estate Agents Spend on Marketing? How to Engage Your Online Audience for Long-Lasting Success Why is Plagiarism Such a Big Deal? Resume Service Review: Why Everyone Should Use It
adbanner