ember.jsrsvp-promise

how to update controller after RSVP.allSettled


After all rsvp promises are done in ember controller, how can I save all error status in controller and update DOM? I got undefined 'this', controller no longer accessible.

export default class someController extends Controller {
  @tracked errorlist = [];

  @action someAction {
    RSVP.allSettled(prommises).then(function(retarray){
      retarray.forEach((retstate) => {
        if (retstate.state == 'rejected') {
          this.errorlist.push(stateRet.reason);   
          //'this' undefined, how to update errlist?
        }
      });
    })
  }
}

Solution

  • There are a few things you could try, but this (less elegant) solution should give you the result you’re looking for:

    export default class someController extends Controller {
      @tracked errorlist = [];
    
      @action
      someAction {
        const that = this;
    
        RSVP.allSettled(promises).then(function (retarray) {
          retarray.forEach((retstate) => {
            if (retstate.state == 'rejected') {
              that.errorlist.push(retstate.reason);
            }
          });
        });
      }
    }
    
    

    Personally, I’d move that errorlist.push into its own method on the controller, so you could call something like this:

    export default class someController extends Controller {
      @tracked errorlist = [];
    
      @action
      someAction {
        RSVP
          .allSettled(promises)
          .then((retarray) => retarray.forEach(this.addToErrorIfRejected));
      }
    
      @action
      addToErrorIfRejected({ state, reason }) {
        if (state == 'rejected') this.errorlist.push(reason);
      }
    }