Skip to main content
14 of 16
added 4 characters in body
Alireza
  • 104.3k
  • 27
  • 277
  • 173

This is one of the places which two ways data binding 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 ways data binding or store concept this issue is simply fixed for you, so in easy word, 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, same with callback or subscribe function on 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(); //call happens here
});

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

Alireza
  • 104.3k
  • 27
  • 277
  • 173