简体   繁体   中英

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: https://ember-twiddle.com/c82fb0e11641703f118e867b45403654?numColumns=2&openFiles=controllers.application.js%2Chelpers.findby.js

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?

I think you just should call recompute !

So something like this:

function findBy([array, key, value]) {
    let content = Ember.get(array, 'content');

    if(!content) {
        array.then(() => this.recompute());
        return null;
    }

    return content.findBy(key, value) || null;
}

What you tried is not possible. If you write return .then(() => <here>); , you return the arrow function not the parent function. The parent function returned long before and well, it will not even wait for promises.

But you can always call .recompute to well, recompute, and this will work for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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