2

ajax 呼び出しを単純な promise としてラップできる単純な rsvp ヘルパーがあります。

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 を返し、成功した場合でも)。上記のように、コントローラーがモデルを「thenable」として呼び出すことができるようにするには、モデルでこの remove メソッドから「チェーンされた約束」を返すにはどうすればよいですか?

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 に答える