如何返回延期的Promise并使用Ember.Deferred创建模型? [英] How to return a deferred promise and create a model with Ember.Deferred?

查看:55
本文介绍了如何返回延期的Promise并使用Ember.Deferred创建模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在应用程序中创建 User.current(),它使用 $。getJSON('从服务器中提取数据/ users / current',function(data){...}); 。我正在使用Discourse使用的Singleton方法,该方法执行以下操作:

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({});
        }
});

在我的 User 单例模型中,我已将 createCurrent 重写如下:

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);
                        }));
                });
        }
});

用户是普通的Ember对象模型:

User is a normal Ember object model:

Dashboard.User = Ember.Object.extend({

});

这确实从服务器请求数据,但该功能未设置 User.current()正确-当我检查它时, User.current()没有应设置的属性,例如名称

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.

如何使用Ember的延期和承诺来返回并设置当前用户?

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

推荐答案

这是因为您要在用户处返回诺言。

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.

或使用Ember Data使用的Promise Proxy模式(一旦解决,就可以将诺言用作对象)

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 });
}

这篇关于如何返回延期的Promise并使用Ember.Deferred创建模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆