2

我有一个简单的 rsvp 助手,可以让我将 ajax 调用包装为一个简单的承诺

var PromiseMixin = Ember.Object.create({
    promise: function(url, type, hash) {
        return new Ember.RSVP.Promise(function(resolve, reject) {
            hash.success = function(json) {
                return Ember.run(null, resolve, json);
            };
            hash.error = function(json) {
                if (json && json.then) {
                    json.then = null;
                }
                return Ember.run(null, reject, json);
            };
            $.ajax(hash);
        });
    }
});

这很好用,并且可以像您期望的那样。问题是当我的代码需要另一个首先包装这个低级别的承诺时。

例子

在我的 ember 控制器中,我可能会这样做

        Appointment.remove(this.store, appointment).then(function() {
            router.transitionTo('appointments');
        }, function() {
            self.set('formErrors', 'The appointment could not be deleted');
        });

在我的约会模型中,我这样做是为了“删除”

remove: function(store, appointment) {
    return this.xhr('/api/appointments/99/', 'DELETE').then(function() {
        store.remove(appointment);
        //but how I do return as a promise?
    }, function() {
        //and how can I return/bubble up the failure from the xhr I just sent over?
    });
},
xhr: function(url, type, hash) {
    hash = hash || {};
    hash.url = url;
    hash.type = type;
    hash.dataType = "json";
    return PromiseMixin.promise(url, type, hash);
}

当前我的控制器始终处于“失败”状态(即使我的 ajax 方法返回 204 并且成功)。如何在我的模型中从这个 remove 方法执行“链式承诺”返回,以使控制器能够像上面那样将其作为“thenable”调用?

4

1 回答 1

3

你不能做这样的事情吗?

remove: function(store, appointment) {
    var self= this;
    return new Ember.RSVP.Promise(function(resolve,reject) {
        self.xhr('/api/appointments/99/', 'DELETE').then(function(arg) {
            store.remove(appointment);
            resolve(arg);
        }, function(err) {
            reject(err);
        });
    });
},
于 2014-08-30T23:55:00.207 回答