首页  >  问答  >  正文

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

我有一个 Ember.js 组件,我尝试使用计算属性来根据异步 RSVP 承诺的结果确定其可见性。但是,计算属性似乎没有等待承诺解析,导致 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;
    }),
});

如您所见,getCount 计算属性正在调用 countService 注入服务上的方法 getCount()。此方法返回一个用计数值解析的承诺。

isVisible 计算属性中,我尝试访问 getCount 计算属性返回的 count 值。但是,当我在调试期间记录 count 的值时,它显示为 未定义,即使此时承诺应该已解决。

我不确定为什么计算属性在尝试访问值之前不等待承诺解析。我在实施中遗漏了什么吗?有没有更好的方法来处理 Ember.js 计算属性中的异步依赖关系?

任何帮助或见解将不胜感激!

P粉549412038P粉549412038401 天前2568

全部回复(1)我来回复

  • P粉505917590

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

    请您尝试一次吗?我还没有测试过,但希望这是有道理的。

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

    回复
    0
  • 取消回复