How do I return the response from an asynchronous call?

0 like 0 dislike
17 views

I have a function foo which makes an Ajax request. How can I return the response from foo?

I tried returning the value from the success callback, as well as assigning the response to a local variable inside the function and returning that one, but none of those ways actually return the response.

by (1.2k points) | 17 views

1 Answer

0 like 0 dislike

Embrace the asynchronous nature of JavaScript! While certain asynchronous operations provide synchronous counterparts (so does "Ajax"), it's generally discouraged to use them, especially in a browser context.

Why is it bad do you ask?

JavaScript runs in the UI thread of the browser and any long-running process will lock the UI, making it unresponsive. Additionally, there is an upper limit on the execution time for JavaScript and the browser will ask the user whether to continue the execution or not.

All of this is really bad user experience. The user won't be able to tell whether everything is working fine or not. Furthermore, the effect will be worse for users with a slow connection.

In the following we will look at three different solutions that are all building on top of each other:

  • Promises with async/await (ES2017+, available in older browsers if you use a transpiler or regenerator)
  • Callbacks (popular in node)
  • Promises with then() (ES2015+, available in older browsers if you use one of the many promise libraries)
by (230 points)

Related questions

1 like 0 dislike
1 answer
0 like 0 dislike
1 answer
0 like 0 dislike
1 answer
110,608 questions
257,186 answers
0 comments
1,118 users