This is one of the places which two ways-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, ReactAngular, React, or any other frameworks which do two ways data bindingtwo-way data binding or store conceptstore concept, this issue is simply fixed for you, so in easy wordwords, 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 javascriptJavaScript or jQueryjQuery for example as you asked in this question?
You can use a callbackcallback, promisepromise and recently observableobservable to handle it for you, for. 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 subscribesubscribe function on observablean observable.
For example, in your case which you are using jQueryjQuery, you can do something like this:
$(document).ready(function(){
function foo() {
$.ajax({url: "api/data", success: function(data){
fooDone(data); //after 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 about promisespromises and observablesobservables which are newer ways to do this async stuffsstuff.