【问题标题】:How to chain a RSVP promise and return the original reject/success functions?如何链接 RSVP 承诺并返回原始拒绝/成功函数?
【发布时间】:2014-08-30 23:45:38
【问题描述】:

我有一个简单的 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”调用?

【问题讨论】:

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


    【解决方案1】:

    你不能这样做吗?

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

    【讨论】:

    • BOOM 你成功了,我的朋友!对不起之前的(不正确的评论)。正如您所说,这100%有效!再次感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-25
    • 2018-02-11
    • 1970-01-01
    • 1970-01-01
    • 2019-11-25
    • 1970-01-01
    相关资源
    最近更新 更多