Ember.js computed properties don't wait for async RSVP promises
P粉549412038
P粉549412038 2023-09-13 23:28:44
0
1
2599

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粉549412038
P粉549412038

reply all(1)
P粉505917590

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;
  }),
});
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template