简体   繁体   中英

Using a Promise in a Computed Property on an Ember model

I have a model, let's call it Task, that has a property assignee. I have another model Admin, that's a set of admins. On task, I want to add a property, admin, that looks up the assignee from the admins by email and returns that admin.

The primary key on Admin is not email, and in Ember Model, it doesn't look like it's possible to create a belongsTo association on any key other than the primary key. The reason I send over email rather than an id is that the admin doesn't always exist.

The Task model looks something like this:

import Em from 'ember';
import Admin from 'project/models/admin';
import PromiseObject from 'project/lib/promise-object';

var Task = Em.Model.extend({
  id: Em.attr(),
  name: Em.attr(),
  assignee: Em.attr(),
  admin: function() {
    return PromiseObject.create({
      promise: Admin.fetch({ email: this.get('assignee') })
    }).then(function(json) {
      return Admin.create(json);
    }, function() {
      return null;
    });
  }.property('assignee'),
  adminName: Em.computed.oneWay('admin.name')
});

export default Task;

PromiseObject is just extending the PromiseProxyMixin, and looks like this:

import Em from 'ember';
export default Em.ObjectProxy.extend(Em.PromiseProxyMixin);

When I try to access the property, I can see the network requests for the admins going across the wire, and I can see the successful response with the correct details included. However, null is returned for the promise.

I'm looking to include {{task.adminName}} in my templates. I'm a little stumped at this point on the best way of resolving the admin promise correctly in my model.

You aren't returning the PromiseObject , you're returning a chained promise. You should just return the PromiseObject .

admin: function() {
  var promise = $.getJSON("/admin").then(function(json) {
    return Admin.create(json);
  }, function() {
    return null;
  });

  return PromiseObject.create({
    promise: promise
  });
}.property('assignee'),

Example: http://emberjs.jsbin.com/nobima/12/edit

Using Ember Model fetch with an object returns a collection, not a model (unless of course you're fetch isn't Ember Model). So json isn't what's being returned at that point. You probably want to do something along these lines.

admin: function() {
  var promise = Admin.fetch({ email: this.get('assignee') }).then(function(collection){
    return collection.get('firstObject');
  }, function() {
    return null;
  });

  return PromiseObject.create({
    promise: promise
  });
}.property('assignee'),

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