Quantcast
Channel: How do I return the response from an asynchronous call? - Stack Overflow
Viewing all articles
Browse latest Browse all 44

Answer by Anish K. for How do I return the response from an asynchronous call?

$
0
0

It's a very common issue we face while struggling with the 'mysteries' of JavaScript. Let me try demystifying this mystery today.

Let's start with a simple JavaScript function:

function foo(){    // Do something    return 'wohoo';}let bar = foo(); // 'bar' is 'wohoo' here

That's a simple synchronous function call (where each line of code is 'finished with its job' before the next one in sequence), and the result is same as expected.

Now let's add a bit of twist, by introducing a little delay in our function, so that all lines of code are not 'finished' in sequence. Thus, it will emulate the asynchronous behavior of the function:

function foo(){    setTimeout( ()=> {        return 'wohoo';   }, 1000)}let bar = foo() // 'bar' is undefined here

So there you go; that delay just broke the functionality we expected! But what exactly happened? Well, it's actually pretty logical if you look at the code.

The function foo(), upon execution, returns nothing (thus returned value is undefined), but it does start a timer, which executes a function after 1 second to return 'wohoo'. But as you can see, the value that's assigned to bar is the immediately returned stuff from foo(), which is nothing, i.e., just undefined.

So, how do we tackle this issue?

Let's ask our function for a promise.Promise is really about what it means: it means that the function guarantees you to provide with any output it gets in future. So let's see it in action for our little problem above:

function foo(){   return new Promise((resolve, reject) => { // I want foo() to PROMISE me something    setTimeout ( function(){      // Promise is RESOLVED, when the execution reaches this line of code       resolve('wohoo') // After 1 second, RESOLVE the promise with value 'wohoo'    }, 1000 )  })}let bar;foo().then( res => {    bar = res;    console.log(bar) // Will print 'wohoo'});

Thus, the summary is - to tackle the asynchronous functions like Ajax-based calls, etc., you can use a promise to resolve the value (which you intend to return). Thus, in short you resolve value instead of returning, in asynchronous functions.

UPDATE (Promises with async/await)

Apart from using then/catch to work with promises, there exists one more approach. The idea is to recognize an asynchronous function and then wait for the promises to resolve, before moving to the next line of code. It's still just the promises under the hood, but with a different syntactical approach. To make things clearer, you can find a comparison below:

then/catch version:

function saveUsers(){     getUsers()      .then(users => {         saveSomewhere(users);      })      .catch(err => {          console.error(err);       }) }

async/await version:

  async function saveUsers(){     try{        let users = await getUsers()        saveSomewhere(users);     }     catch(err){        console.error(err);     }  }

Viewing all articles
Browse latest Browse all 44

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>