Ember.js 计算属性不等待异步 RSVP 承诺
P粉549412038
P粉549412038 2023-09-13 23:28:44
0
1
2684

我有一个 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粉549412038
P粉549412038

全部回复(1)
P粉505917590

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

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;
  }),
});
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板