0

I have code like this waiting async method which put the value in class member.

And then I want to use the class member in then function.

I guess I understood the behaivor, function in then(myThenFunc) is set ready and myClass instance is copied before ajax returns the value.

So,but now, how can I use the myClass value in myThenFunc

If I could pass the pointer &myClass in advance to myThenFunc......

class MyClass{
    constructor(){

        this.data1 = []
        this.data2 = []

        var p1 = $.ajax({
                type: "GET",
                url: data1-api,
                success: function(response) {
                    console.log(response);
                    this.data1 = response;
                }
            });

        var p2 = $.ajax({
                type: "GET",
                url: data2-api,
                success: function(response) {
                    console.log(response);
                    this.data2 = response;

                }
            });

        this.apiPromises = Promise.all([p1,p2]);
    }    
}
var myClass = new MyClass();
$(function() {
    baseHdl.apiPromises.then(function (value) {// name this `myThenFunc`
        console.log("finish all");
        console.log(myClass);// it has instance but.....
        console.log(myClass.data1); // only blank array.
whitebear
  • 11,200
  • 24
  • 114
  • 237
  • Your `this` inside the `success` callback isn't referring to the instance, it's referring to the jqXHR object. Use an arrow function instead: `success: (response) => { console.log(response); this.data1 = response; }` – CertainPerformance Feb 09 '20 at 08:31
  • If you don't actually need to do anything else synchronous inside the `success` callback, it might be better to consume the response in the lower `.then`: https://jsfiddle.net/ngfbvx16/ – CertainPerformance Feb 09 '20 at 08:34
  • Thank you very much. I think I misunderstood where the problem is. I just changed `this.data1 = response;` -> `myClass.data1 = response;` as @CertainPerformance told me it works. – whitebear Feb 10 '20 at 09:39

0 Answers0