Component that could receive a Promise or a Non-Promise object

Hello,

I have a Chart component that could receive data to render as a Promise or as a regular JavaScript Object. It should be able to handle both cases within didInsertElement event. How can I safely recognize that data is a Promise or not?

{{ember-chart data=chartData}}

// components/ember-chart
import Ember from "ember";

export default Ember.Component.extend({

  didInsertElement: function() {
    var canvas = this.get('element');
    var context = canvas.getContext('2d');
    canvas.width = Ember.$(canvas).parent().width();
    canvas.height = Ember.$(canvas).parent().height();

    var _this = this;
    //*********** if this.get('data') is not a Promise BOOM!
    this.get('data').then(function(chartData){
      var data = chartData;
      // do other stuff before rendering
    });
   },

Thanks

I’ve been checking if it has ‘then’. But there’s probably a more intelligent way to do this.

You should wrap the parameter in a promise, and thereby always treat it like a promise:

Ember.RSVP.Promise.resolve(this.get('data')).then(function(chartData) {

});

If it is a promise already there will be no issue.

2 Likes

@varblob I was already checking ‘promise’ instead of ‘then’, but yes, it seemed awkward.

   if (data.hasOwnProperty('promise')) {
      this.get('data').then(function(chartData){
        data = chartData;
        // do something
      });
    } else {
      // do other thing
   }

@buuda that’s pretty neat. Thanks!