ember.js - 如何根据promise返回数据

标签 ember.js concurrency

我在模型中有一个“虚拟属性”,我希望 setter 在返回值之前等待 promise :

idShop:Ember.computed('shop',function(){
    get(key){
      return this.get('shop').id;
    },
    set(k,v){
      this.get('store').findRecord('shop',key)
      .then(shop =>{ 
        this.set('shop', shop)
      })
    }
  })

在集合中,我需要在 findRecord 后返回 k(key) 或 shop.id,并且解决了 then 问题。我怎样才能做到这一点?

最佳答案

所以这是 Ember Concurrency. 的一个很好的用例

Ember 并发 (EC) 在其 task() 方法内使用生成器函数 function * () {} 来更轻松地管理此类内容。任务还提供一些实用程序属性来显示它当前是正在运行还是空闲(也称为加载数据或完成加载数据)。

这是我的设置方法(ember 2.17 及更高版本的代码)

import {task} from 'ember-concurrency';
import {computed} from '@ember/object';
# skip ahead to later in the code...
shop: null,
loadShop: task(function*(key) {
   let shop = yield this.get('store').findRecord('shop', key)
   this.set('shop', shop)
}),
shopId: computed('shop', function() {
  if (this.get('shop') {
    return this.get('shop.id);
  } else {
     return null;
  }
})

根据您的具体用例,当您知道 id 是什么时(可能在 init Hook 或在单独的方法中)

(注意:将属性作为计算属性的一部分进行变异是一种不好的做法。计算属性确实应该是无状态的。)

关于ember.js - 如何根据promise返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51541497/

相关文章:

java - 在 Java 中使用多个线程

java - 死你threadpoolexecutor

ember.js - Ember : how to handle unexpected routes?

node.js - 运行 "ember server"失败并出现错误

java - newFixedThreadPool 的内部工作

ruby - 我如何使用 Celluloid 并行执行我的插件?

Ember.js:在 before/afterModel Hook 中访问 queryParams

namespaces - Ember.js 模型中的保留属性名称

javascript - 在 ember js 中从多个 Web 服务获取数据的最佳方法是什么?

java - 并行迁移巨大的 XML 文件列表