How to resolve a promise within a template?


#1

Hi,

I try to do something like this in a model:

test: function () {
  return this.get( 'something' ).then( function ( something ) {
    return something.get( 'value' );
  });
}

The problem is that the template does not resolve the promise object. What can I do to solve this? I found a few posts about this problem but I didn’t understand how to solve it.

Thanks


Ember data blocking initial page load
#2

I recommend using the ObjectProxy along with the PromiseProxyMixin for your scenario.

When the promise is still pending, then test.get('isPending') will be true. So your template can show a loading message as it’s waiting for the promise to be fulfilled. And once the promise has been fulfilled, then the template can show the value from the promise result.

You’ll first need to create a new object that uses ObjectProxy and extends PromiseProxyMixin

var PromiseObject = Ember.ObjectProxy.extend(Ember.PromiseProxyMixin)

That’s kind of annoying to have to manually define the PromiseObject before you can use it. Ember data has the DS.PromiseObject that does this for you, so you can use that if you’re using Ember data within your project.

Here’s what your test function will look like using a promise object:

test: function() {
  return DS.PromiseObject.create({
    promise: this.get('something')
  });
}

And here is how your template can take advantage of the promise object:

{{#if test.isPending}}
  Loading...
{{else}}
  value: {{test.value}}
{{/if}}

#3

Thanks for your reply. This helped me a lot.

{{test.value}}

didn’t work. I tried:

{{test.content}}

and now everything works beautifully.