0

Im currently trying to use a Promise to resolve fetching models from database. In the following was:

Promise.resolve(app.Departments.fetch()).then(function(response){
    console.log(response);
    this.$el.html( this.template( {depts: app.Departments.toJSON()} ));
    this.$form = this.$('#form-employee');
    this.$form.validator();
    return this;
})

Consider everything is inside the render method and the method is inside a Backbone.View.extend({}) object. The problem is that inside the Promise.resolve() function the context of this is different from the context inside the View object which it throws an error not knowing what does this refers to. Is there anyway to pass to Promise.resolve the correct context of this?

Diego Gallegos
  • 1,722
  • 2
  • 18
  • 31
  • Notice you are calling `then` with a callback, not `resolve`. – Bergi Mar 01 '16 at 16:14
  • Can you enlighten on this topic? I know then can be both used when resolving and rejecting stages of Promises. – Diego Gallegos Mar 01 '16 at 17:30
  • The `then` method works on any promises regardless of their state. What my comment tried to emphasise that your problem stems from how `then` handles the callback, and has nothing to do where the promise comes from - be it `Promise.resolve` or anything else – Bergi Mar 01 '16 at 17:38
  • Can you show an example of it? Is there any question you can refer me too.? – Diego Gallegos Mar 01 '16 at 17:57
  • The correct usage of then. I would appreciate it. – Diego Gallegos Mar 01 '16 at 18:12
  • You are already using it correctly? The callback is to blame here. See the linked duplicate for examples. – Bergi Mar 01 '16 at 18:31

1 Answers1

1

Use a local reference for this:

var self=this;
Promise.resolve(app.Departments.fetch()).then(function(response){
   console.log(response);
   self.$el.html( self.template( {depts: app.Departments.toJSON()} ));
   self.$form = this.$('#form-employee');
   self.$form.validator();
   return self;
})
Alex Suleap
  • 559
  • 4
  • 12