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

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

$
0
0

This is one of the places which two-way data binding or store concept that's used in many new JavaScript frameworks will work great for you...

So if you are using Angular, React, or any other frameworks which do two-way data binding or store concept, this issue is simply fixed for you, so in easy words, your result is undefined at the first stage, so you have got result = undefined before you receive the data, then as soon as you get the result, it will be updated and get assigned to the new value which response of your Ajax call...

But how you can do it in pure JavaScript or jQuery for example as you asked in this question?

You can use a callback, promise and recently observable to handle it for you. For example, in promises we have some function like success() or then() which will be executed when your data is ready for you. The same with callback or the subscribe function on an observable.

For example, in your case which you are using jQuery, you can do something like this:

$(document).ready(function(){    function foo() {        $.ajax({url: "api/data", success: function(data){            fooDone(data); // After we have data, we pass it to fooDone        }});    };    function fooDone(data) {        console.log(data); // fooDone has the data and console.log it    };    foo(); // The call happens here});

For more information, study promises and observables which are newer ways to do this async stuff.


Viewing all articles
Browse latest Browse all 46

Trending Articles