mercredi 30 mars 2016

EmberJS: How to make a helper that can return data from a promise

I created a {{findby}} helper that is super useful for picking an item out of an array, but i ran into a problem. The helper does not like to call findBy() on an array which is a promiseArray.

So the helper was modified to do this:

export function findby([array, key, value]) {
  let isPromiseArray = Ember.typeOf(array.then) === 'function';
  if (isPromiseArray) {
    array.then((arr) => {
      return arr.findBy(key, value) || null;
    });
  } else {
    return array.findBy(key, value) || null;
  }
}

export default Ember.Helper.helper(findby);

the idea being of course, if a passed array happens to be a PromiseArray, use a then() before trying to call findBy().

The problem is that I cant seem to return anything in this case.. returning from inside the then() does not seem to actually close out the helper function so the helper returns undefined.

If i try to do:

return array.then((arr) => {
  return arr.findBy(key, value) || null;
});

then just the promise itself gets returned from the helper.

Here is a twiddle of what I have attempted: http://ift.tt/1RLHFhv

THe question seems to be a general one for helpers: Is there a way to return data from a promise/then() function in a helper? I wonder if what i want to do is even possible with a helper?




Aucun commentaire:

Enregistrer un commentaire