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

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

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

  1. import Component from '@ember/component';
  2. import { computed } from '@ember/object';
  3. import { inject as service } from '@ember/service';
  4. import RSVP from 'rsvp';
  5. export default Component.extend({
  6. classNames: ['count'],
  7. countService: service('count'),
  8. getCount: computed(function () {
  9. debugger;
  10. RSVP.all([
  11. this.get('countService').getCount()
  12. ]).then(([count]) => {
  13. return Number(count);
  14. });
  15. }),
  16. isVisible: computed('getCount', function () {
  17. debugger;
  18. let count = this.get('getCount');
  19. return count !== undefined && count > 0;
  20. }),
  21. });

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

tpgth1q7

tpgth1q71#

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

  1. import Component from '@ember/component';
  2. import { computed } from '@ember/object';
  3. import { inject as service } from '@ember/service';
  4. import RSVP from 'rsvp';
  5. export default Component.extend({
  6. classNames: ['count'],
  7. countService: service('count'),
  8. getCount: computed(function() {
  9. return RSVP.all([this.get('countService').getCount()]).then(([count]) => {
  10. return Number(count);
  11. });
  12. }),
  13. isVisible: computed('getCount', function() {
  14. let count = this.get('getCount');
  15. return count !== undefined && count > 0;
  16. }),
  17. });

字符串

展开查看全部

相关问题