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

Answer by Zia for How do I return the response from an asynchronous call?

$
0
0

In JS, when an asynchronous function is called, it returns a Promise. If you want to return a value from the function, you need to ensure you are properly handling this Promise.

There is an example:

async function foo() {  var res;  await asyncRequest().then(function(response) {    res = response;  });  return res;}

// Call the function and handle it's result:

foo().then(function(res) {  console.log(res);});

In the above code, foo is an asynchronous function which makes an asynchronous request. The await keyword is used to pause the execution of the function until the Promise is resolved 🤚. Once the Promise is resolved, the response is assigned to the result variable, that then returned by the function.

When calling the function, since it returns a Promise, you need to use .then() to handle the result after the Promise is resolved.

async function bar() {  var res = await foo();  console.log(res);}

Remember, you can only use await inside an async function(). If you’re not in an async function and want to use await, you will get a syntax error.


Viewing all articles
Browse latest Browse all 46

Trending Articles



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