Quantcast
Viewing all articles
Browse latest Browse all 44

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

Using ES2017 you should have this as the function declaration.

async function foo() {  var response = await $.ajax({url: '...'})  return response;}

And executing it like this.

(async function() {  try {    var result = await foo()    console.log(result)  } catch (e) {}})()

Or the Promise syntax.

foo().then(response => {  console.log(response)}).catch(error => {  console.log(error)})

Stack Snippet that demonstrates the code above.

// The function declaration:async function foo() {  var response = await $.ajax({    url: 'https://jsonplaceholder.typicode.com/todos/1'  })  return response;}// Execute it like this:(async function() {  try {    var result = await foo()    console.log(result)  } catch (e) {}})()// Or use Promise syntax:foo().then(response => {  console.log(response)}).catch(error => {  console.log(error)})
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

Viewing all articles
Browse latest Browse all 44

Trending Articles



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