Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a Promise from a Computed Property

I realize there have been several questions similar to this, but none of those answers seems to be resolving my issue. My objective is to take a list of language's, and filter them so that my template can display a subset of the full list.

I started off by verifying that my computed property is working:

MyController.js

// Works as expected
languagesFiltered: function() {
   return this.get('languages');
}.property('languages')

Then I added in a filter function, but here's where I ran into trouble:

MyController.js

languagesFiltered: function() {
   // console.log shows that languages is actually a promise
   var languages = this.get('languages');

   // all of this returns a promise, but Handlebars can't handle the promise
   return languages.then( function( languagesArray ) {
      return languagesArray.filter( function( item, index, enumerable) { 
         return item.get('name') !== 'English';
      });
   })
}.property('languages')

I'm attempting to use the Ember.Array.filter method (http://emberjs.com/api/classes/Ember.ArrayProxy.html#method_filter). The filter seems to be working correctly, but now languagesFiltered returns a promise, and Handlebars can't handle that.

I tried one last alternative:

MyController.js

languagesFiltered: function() {
     var languages = this.get('languages');

     // "return languages;" works
     // But "return languages.filter" returns an empty array
     return languages.filter( function( item, index, enumerable ) {
         console.log(item);
         return true;
   });
}.property('languages')

And console.log(item) never gets called. So my questions are:

  • What is the best way to implement the simple filter I'm after?
  • This is a read-only computed property, but what are best practices for handling async values in computed properties?

I'm using Ember 1.7.0-beta4, Ember Data 1.0.0-beta10, and ember-cli 0.44. I'd upgrade to Ember 1.7.0, but there's a small bug that affects another part of our app, so we're waiting until 1.7.1. Thanks for your input!

like image 887
Josh Padnick Avatar asked Nov 30 '22 01:11

Josh Padnick


1 Answers

You can try returning a PromiseArray instead of just the promise.

You should be able to do something like..

languagesFiltered: function() {
   // all of this returns a promise, but Handlebars can't handle the promise
   var promise = this.get('languages').then( function( languagesArray ) {
      return languagesArray.filter( function( item, index, enumerable) { 
         return item.get('name') !== 'English';
      });
   })

   return DS.PromiseArray.create({
      promise: promise
   });

}.property('languages')
like image 180
tikotzky Avatar answered Dec 02 '22 15:12

tikotzky