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

JavascriptFront End TechnologyObject Oriented Programming

There are multiple ways to return the response from an asynchronous call in javascript. Let us understand the problem first. Say you have a function called foo that is asynchronous and will give the data after some time. It can do this in 2 ways. It can either accept a callback that it'll call when it is ready to execute with the data. Or it can return a promise.

For example, the setTimeout function accepts a callback and executes it after a fixed amount of time. so lets say that you go with the first approach, then you can pass the function in the setTimeout.

Example

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

Output

100

This will call the setTimeout function with a callback which will execute after 1000 ms. when that function is executed, it'll call the passed callback(cb) with the value returned from the setTimeout's callback.

Using Promises

You can also do this using promises. Wrap your async function with a promise and resolve this promise with the function's return value. You can the chain the then method and pass it a callback to use the value returned from the async function.

,

Example

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

Output

100
raja
Published on 18-Sep-2019 13:20:23
Advertisements