How to return a deferred promise and create a model with Ember.Deferred?

与世无争的帅哥 提交于 2019-12-23 18:34:01

问题


I'm trying to create a User.current() in my application, which pulls data from my server using $.getJSON('/users/current', function(data) { ... });. I am using the Singleton method that Discourse uses, which does the following:

Dashboard.Singleton = Ember.Mixin.create({
        // See https://github.com/discourse/discourse/blob/master/app/assets/javascripts/discourse/mixins/singleton.js

        current: function() {
                if (!this._current) {
                        this._current = this.createCurrent();
                }
                return this._current;
        },

        createCurrent: function() {
                return this.create({});
        }
});

And in my User singleton model, I've rewritten createCurrent as follows:

Dashboard.User.reopenClass(Dashboard.Singleton, {
        createCurrent: function() {
                return Ember.Deferred.promise(function(p) {
                        return p.resolve($.getJSON('/users/current').then(function(data) {
                                return Dashboard.User.create(data);
                        }));
                });
        }
});

User is a normal Ember object model:

Dashboard.User = Ember.Object.extend({

});

This does request the data from the server, but the function is not setting User.current() correctly - when I inspect it, User.current() has none of the properties that should be set, such as name.

How can I return and set the current user using Ember's deferred and promises?


回答1:


That's cause you're returning the promise in place of the user.

Why don't you create the user, then fill in the properties later.

Or use the Promise Proxy pattern that Ember Data uses (the promise can be used as the object once resolved)

DS.PromiseObject = Ember.ObjectProxy.extend(Ember.PromiseProxyMixin);

function promiseObject(promise) {
  return DS.PromiseObject.create({ promise: promise });
}



回答2:


Since $.getJSON('/users/current') returns a promise, might as well use that.

createCurrent: function() {
                return $.getJSON('/users/current').then(function(data) {
                       return Dashboard.User.create(data);
                });
    }

Then you need to keep in mind that createCurrent returns a promise, not the object itself so you will need to:

current: function() {
            if (!this._current) {
                    var that = this;
                    this.fetching = true;
                    this.createCurrent().then(function(val) {
                        that.fetching = false;
                        that._current = val;
                    });
            }
            return this._current;
    },


来源:https://stackoverflow.com/questions/20597087/how-to-return-a-deferred-promise-and-create-a-model-with-ember-deferred

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!