首頁  >  問答  >  主體

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 天前2565

全部回覆(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
  • 取消回覆