在Ember.RSVP.hash

时间:2015-06-26 19:36:29

标签: ember.js hash promise

我已经把头发拉了几个小时,所以我想我只是问:)

在我的路线的模型钩子中,我从会话商店抓取帐户ID。我还使用(当前)硬编码ID返回布局的Ember哈希值:

model: function() {
  var accountId = this.get('session.currentUser').then(function(user) {
    return user;
  }).then(function(user) {
    return user.get('account');
  }).then(function(account) {
    var accountId = parseInt(account.get('id'));
    console.log(accountId); // outputs 2
    return accountId;
  });
  return Ember.RSVP.hash({
    layouts: this.store.query('layout', { account_id: 2 })
  });
},

/* {{log layouts}} in the template returns the correct list of layouts */

但是,当我尝试在哈希中使用第一个promise的值时,如下所示:

return Ember.RSVP.hash({
  layouts: this.store.query('layout', { account_id: accountId })
});

我收到以下错误:

  

您必须将解析器函数作为promise构造函数的第一个参数传递

     

TypeError:您必须将解析器函数作为promise构造函数的第一个参数传递

我几乎可以理解这一点,因为在调用哈希函数之前,可能没有解决accountID承诺。

但后来我尝试了:

var _this = this;
var accountId = this.get('session.currentUser').then(function(user) {
  return user;
}).then(function(user) {
  return user.get('account');
}).then(function(account) {
  var accountId = parseInt(account.get('id'));
  console.log(accountId); // outputs 2
  return accountId;
}).then(function(accountId) {
  console.log(accountId); // outputs 2
  return Ember.RSVP.hash({
    layouts: _this.store.query('layout', { account_id: accountId })
  });
});

这不会产生任何错误,但模板中的{{log layouts}}会返回' undefined'。

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

而不是在最后返回哈希,而是以相反的方式构建你的承诺:

var _this = this;
return Ember.RSVP.hash({
  layouts: this.get('session.currentUser').then(function(user) {
      return user;
  }).then(function(user) {
      return user.get('account');
  }).then(function(account) {
      return parseInt(account.get('id'), 10);
  }).then(function(accountId) {
      return _this.store.query('layout', { account_id: accountId });
  })
});