Domanda

Sto cercando di creare un albero di promesse in Ember.

        return this.store.find('session', 'session').then(function(session) {
            if (session.get('isEmpty')) {
                return this.store.createRecord('session').save().then(function(session) {
                    session.set('id', 'session');

                    return session.save();
                }.bind(this));
            } else {
                return session;
            }
        }.bind(this), function(session) {
            return this.store.createRecord('session').save().then(function(session) {
                session.set('id', 'session');

                return session.save();
            }.bind(this));
        }.bind(this)).then(function(session) {
            this.controllerFor('application').onLanguageChange();

            this.set('localStorage.session', session);

            return session;
        }.bind(this));

Vorrei eseguire le promesse come mostrato.Ricorda che ci sono anche promesse annidate createRecord(..).save().then.È possibile farlo?

Non è esattamente un albero di promesse qui poiché l'ultimo dovrebbe essere eseguito per entrambi i rami.Potrebbe essere, naturalmente, se li metto in una funzione propria.Così come questo:

'successBranch'.then(function(session) {
   setSessionDependents(session);
   return session;
}

'failBranch'.then(function(session) {
   setSessionDependents(session);
   return session;
}

function setSessionDependents(session) {
    this.controllerFor('application').onLanguageChange();

    this.set('localStorage.session', session);
}
È stato utile?

Soluzione

l'ultimo dovrebbe essere eseguito per entrambi i rami

Lo fa in realtà!Se un gestore di errori non throw un'eccezione, l'errore era stato gestito e la promessa si risolve con return valore del gestore.

È possibile farlo?

Sì!Questa è una delle proprietà principali di then, che risolve con promesse annidate.

Tuttavia, potresti semplificare un po ' il tuo codice, dato che hai un sacco di duplicazioni lì dentro:

return this.store.find('session', 'session').then(function(session) {
    if (session.get('isEmpty')) {
        throw new Error("no session found");
    else
        return session;
}).then(null, function(err) {
    return this.store.createRecord('session').save().then(function(session) {
        session.set('id', 'session');
        return session.save();
    });
}.bind(this)).then(function(session) {
    this.controllerFor('application').onLanguageChange();
    this.set('localStorage.session', session);
    return session;
}.bind(this));
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top