简体   繁体   English

在Ember.RSVP.hash中使用承诺的结果

[英]Using the result of a promise in Ember.RSVP.hash

I've been pulling out my hair with this for a few hours now so I thought I'd just ask :) 我已经用这个拉了几个小时了,所以我想我只是问:)

In the model hook of my route, I'm grabbing the account ID from the session store. 在路线的模型挂钩中,我正在从会话存储中获取帐户ID。 I'm also returning an Ember hash of layouts using a (presently) hard-coded 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 */

However, when I try and use the value of the first promise in the hash, as follows: 但是,当我尝试在哈希中使用第一个promise的值时,如下所示:

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

I get the following error: 我收到以下错误:

You must pass a resolver function as the first argument to the promise constructor 您必须将解析器功能作为第一个参数传递给promise构造函数

TypeError: You must pass a resolver function as the first argument to the promise constructor TypeError:您必须将解析器函数作为第一个参数传递给promise构造函数

I can almost understand this, as perhaps the accountID promise isn't resolved before the hash function is called. 我几乎可以理解这一点,因为在调用哈希函数之前,也许无法解析accountID承诺。

But then I tried: 但是后来我尝试了:

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 })
  });
});

This does not give any errors, but {{log layouts}} in the template returns 'undefined'. 这不会产生任何错误,但是模板中的{{log layouts}}返回“ undefined”。

Can anyone help, please? 有人可以帮忙吗?

Instead of returning the hash at the end, structure your promise the other way around: 不要在末尾返回哈希,而是以其他方式构造您的诺言:

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 });
  })
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM