Correct way to handle promises (in a stache file)


#1

I have this component/viewmodel (similar to the one on my previous post: Overwriting methods of a ViewModel (getter))

import Component from 'can-component';
import DefineMap from 'can-define/map/';
import './my-component.less';
import view from './my-component.stache';
import MainModel from 'ozzi-application/models/my-model';

export const ViewModel = DefineMap.extend({
  get mainModelPromise() {
    return MainModel.getList({});
  },
  mainModelValue: {
    get: function(last, set) {
      this.mainModelPromise.then(set);
    }
  }
});

export default Component.extend({
  tag: 'ozzi-apps-my-component',
  ViewModel,
  view
});

So I’m confused in the way I should handle rejections and pending status. It would be great if someone could validate if this two approaches are correct or if there is a better approach. I’ve been struggling with hard to debug rejections and this could help me a lot.

I have:

Approach #1

// aproach #1 using "resolved" mainModelValue
{{#if mainModelPromise.isRejected}}
  rejected!
{{else}}
  <ul>
  {{#each mainModelValue}}
    <li>one line</li>
  {{/each}}
  </ul>
{{/if}}

Approach #2

// approach #2 using a promise
{{#if mainModelPromise.isPending}}
  pending!
{{else}}
  <ul>
  {{#each mainModelPromise.Value}}
    <li>one line</li>
  {{/each}}
  </ul>
{{/if}}

Is there something wrong on those two approaches?
Thanks


#2

I use all three states, since a promise can be either pending, resolved, or rejected. Usually something like this:

{{#if promise.isPending}}

<div class="loading"/>

{{else}}

{{#if promise.isResolved}}

<!-- resolved content-->

{{else}}

<!-- Error! -->

{{/if}}

{{/if}}