如何链接RSVP承诺并返回原始拒绝/成功函数?

时间:2014-08-30 23:45:38

标签: ember.js rsvp.js rsvp-promise

我有一个简单的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);
        });
    }
});

这很有效,然后就像你期望的那样。问题是当我的代码需要另一个承诺,首先包装这个低级别的。

例如

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

        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方法返回“链式承诺”,以使控制器能够像上面那样“调用”它?

1 个答案:

答案 0 :(得分: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);
        });
    });
},