vendredi 26 juin 2015

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 a route, I'm grabbing the account ID from the session store:

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

I'm also returning an Ember hash of layouts using a (presently) hard-coded ID:

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:

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

TypeError: You must pass a resolver function as the first argument to the promise constructor

I can almost understand this, as perhaps the accountID promise isn't resolved before the hash function is called.

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'.

Can anyone help, please?




Aucun commentaire:

Enregistrer un commentaire