Home  >  Q&A  >  body text

Ember.js computed properties don't wait for async RSVP promises

I have an Ember.js component and I'm trying to use a computed property to determine its visibility based on the results of an asynchronous RSVP promise. However, the computed property does not appear to wait for the promise to resolve, resulting in the count object being undefined.

Here is an excerpt of my component code:

import Component from '@ember/component';
import { computed } from '@ember/object';
import { inject as service } from '@ember/service';
import RSVP from 'rsvp';

export default Component.extend({
    classNames: ['count'],
    countService: service('count'),

    getCount: computed(function () {
        debugger;
        RSVP.all([
            this.get('countService').getCount()
        ]).then(([count]) => {
            return Number(count);
        });
    }),

    isVisible: computed('getCount', function () {
        debugger;
        let count = this.get('getCount');
        return count !== undefined && count > 0;
    }),
});

As you can see, the getCount computed property is calling the countService method getCount() on the injected service. This method returns a promise resolved with a count value.

In the isVisible computed property, I am trying to access the count value returned by the getCount computed property. However, when I log the value of count during debugging, it shows up as Undefined, even though the promise should have resolved at this point.

I'm not sure why computed properties don't wait for the promise to resolve before trying to access the value. Am I missing something in my implementation? Is there a better way to handle asynchronous dependencies in Ember.js computed properties?

Any help or insight would be greatly appreciated!

P粉549412038P粉549412038401 days ago2571

reply all(1)I'll reply

  • P粉505917590

    P粉5059175902023-09-14 12:10:20

    Would you please try it once? I haven't tested it yet, but hopefully this makes sense.

    import Component from '@ember/component';
    import { computed } from '@ember/object';
    import { inject as service } from '@ember/service';
    import RSVP from 'rsvp';
    
    export default Component.extend({
      classNames: ['count'],
      countService: service('count'),
    
      getCount: computed(function() {
        return RSVP.all([this.get('countService').getCount()]).then(([count]) => {
          return Number(count);
        });
      }),
    
      isVisible: computed('getCount', function() {
        let count = this.get('getCount');
        return count !== undefined && count > 0;
      }),
    });

    reply
    0
  • Cancelreply