mardi 31 mai 2016

Ember: Return a value or set a model property from Ember promise

If I have a promise, is it possible to return a value from it?

let itemData = [];
model.data.get('products').then(relatedItems => {
  relatedItems.forEach(function(item,index) {
    console.log(item.get('name')); // Product 1, Product 2 etc
    itemData.pushObject(item);
  });
},reject => {
  console.log('error '+reject);
});

If I try and return the itemData array after the promise has resolved I get undefined.

Alternatively (and preferably) I'd like to be able to set a model property when the promise has resolved:

// component code 

itemData:null,
init() {
  let model = this.get('data);
  model.data.get('products').then(relatedItems => {
     relatedItems.forEach(function(item,index) {
        this.set('itemData,item);
     });
  },reject => {
     console.log('error');
  });
}

The reason for all of this is that I need to sort the product items which I can only access via the promise (in this example). Having set the itemData property I was intending to do something like:

sortedItems:computed.sort('itemData','sortProperties'),
sortProperties:['name:desc']




Aucun commentaire:

Enregistrer un commentaire