Ember.js计算属性未等待异步RSVP承诺

l5tcr1uw  于 2023-08-04  发布在  其他
关注(0)|答案(1)|浏览(160)

我有一个Ember.js组件,我试图使用一个computed属性来根据异步RSVP promise的结果确定它的可见性。但是,computed属性似乎没有等待promise解析,导致count对象未定义。
下面是我的组件代码的摘录:

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;
    }),
});

字符串
如您所见,getCountcomputed属性正在countService注入的服务上调用方法getCount()。此方法返回一个使用count值解析的promise。
isVisiblecomputed属性中,我尝试访问getCountcomputed属性返回的count值。然而,当我在调试过程中记录count的值时,它显示为undefined,即使promise应该在那个时候已经解决了。
我不确定为什么computed属性在尝试访问值之前不等待promise解析。我在实现中缺少了什么吗?是否有更好的方法来处理Ember.js计算属性中的异步依赖关系?
任何帮助或见解将不胜感激!

tpgth1q7

tpgth1q71#

你能试一次吗?我还没有测试,但希望这是有意义的。

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;
  }),
});

字符串

相关问题