0

I have a class, with 'tax' var. I need fill this var when the request is complete.

The problem is that if I return into callback, this return is for callback function, not for my method, and if I return in a taxMethod, it is executed before that I have the data, because is async and request async.

class Myclass{

    constructor(){
     this.tax = this.taxMethod()
    }

    taxMethod(){

     let data = 0;
        this.simpleRequest(url,function(data){         

           data = Number(data[0].tx)
           return data //Return of callback

        }.bind(this))
      return data //Empty data
    }
}
Kulin
  • 511
  • 1
  • 4
  • 9
  • 6
    you'll never be able to return asynchronous data from a function ... your choices are - 1. Callback, 2. Promise, 3. Async/Await – Jaromanda X Dec 07 '16 at 07:43
  • 1
    The callback `function(data){}` is fired in a new thread after the server returned data. All you need to do is put the data into `this.tax`, instead of returning it. In `constructor()`, you just call `this.taxMethod()` without assigning it directly to `this.tax`. It's not the cleanest of solutions, but the most basic. – mch Dec 07 '16 at 07:46
  • try to assign some global Valerie, assign it to default, inside taxMethod function, store the value, and use it, after some delay... – nisar Dec 07 '16 at 07:46
  • if you dont know async , use settimeout...but its bad habit... – nisar Dec 07 '16 at 07:47
  • @JaromandaX `await` is just a different way of consuming promises, `taxMethod`/`simpleRequest` would still need to create a promise – Bergi Dec 07 '16 at 07:58
  • @Bergi - I know that, and anyone reading into it would know that, I separated `Promise` and `await` because you can do `Promise` without `await` :p – Jaromanda X Dec 07 '16 at 08:14
  • class MyClass { constructor(){ this.taxMethod(function(data){ data = Number(data[0].txt); this.tax =data; console.log("tax", this.tax); }.bind(this)); } taxMethod(callback){ this.simpleRequest("url", function(data){ callback(data); }); } simpleRequest(url, callback){ setTimeout(function(){ let fakeParm = [{txt:"123.21"}]; callback(fakeParm); }, 1000); } } let myInstance = new MyClass(); – MFAL Dec 07 '16 at 10:30

0 Answers0