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

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

$
0
0

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?

  1. 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

  1. 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>

Viewing all articles
Browse latest Browse all 44

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>