Scope in asynchronous call (Javascript)

3

Let's suppose I had the following method:

this.loadCustomers = function(){
    Request.get("php/loadCustomersAction.php", (function(error, data){
        if(!error)
            this.setCustomers(data);
    }).bind(this));
};

where "Request.get" is a method that performs asynchronous calls.

You can imagine that the "this" in

this.setCustomers()

can keep the same scope as

this.loadCustomers()

without the help of bind when establishing the callback and without making the function synchronous? If so, how could it be done?

    
asked by anonymous 14.06.2017 / 19:14

1 answer

3

There are ways to get around this without using .bind , but remember that it may be the case that .bind is the most useful / simple.

Alternatives:

  • Using alias var self = this

ie: saving a reference of this

this.loadCustomers = function(){
    var self = this;
    Request.get("php/loadCustomersAction.php", function(error, data){
        if(!error) self.setCustomers(data);
    });
};
  • Using () => {}

ie: arrow functions

this.loadCustomers = function(){
    Request.get("php/loadCustomersAction.php", (error, data) => {
        if(!error) this.setCustomers(data);
    });
};

There may be more alternatives, but it depends on how Req.get is implemented. It may be worth testing calling this Req.get by forcing the context:

this.loadCustomers = function(){
    Request.get.call(this, "php/loadCustomersAction.php", function (error, data){
        if(!error) this.setCustomers(data);
    });
};

which with some luck allows, if the implementation allows, pass the context to the callback.

    
15.06.2017 / 00:06