Many answers do not answer how to obtain the variable inside the callback function and use it later on.
var myvar = '';var myvar2 = ajax("GET", "/test", "acrive=1").then(function(result) { myvar = result.data.myvar # <-- How to populate myvar? return myvar;})console.log(myvar) # returns undefinedconsole.log(myvar2)# returns a promise
Why
The reason is that result.data is a promise. Meaning it is sort of a unstable changing thing and you cannot use it like a variable.
How to Use it then?
- Use js to turn it into HTML
.then(function(result) { myvar = result.data.myvar $('#result').html(myvar) # <-- use the result in the dom})
This will turn it into a dom "constant" to display
- Use virtual dom like Vue.js variable. The vue.js variables are responsive and automatically connect to the ajax promise so you do not have to do anything.
myvar = result.data.myvar # <-- How to populate myvar?var app = new Vue({ el: '#app', data: { myvar: '' }, methods: { getData() { var myvar = ''; var self = this; ajax("GET", "/test", "acrive=1").then(function(result) { myvar = result.data.myvar self.myvar = myvar; #populate this }) }});
HTML<div id='app'><div> {{ myvar }} </div></div>