How to create a tree of promises?

两盒软妹~` 提交于 2019-12-24 09:57:36

问题


I'm trying to create a tree of promises 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));

I would like to execute the promises as shown. Mention that there are also nested promises createRecord(..).save().then. Is it possible to do that?

It's not exactly a tree of promises here since the last one should be executed for both branches. It could be of course if I put those in an own function. So like this:

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

回答1:


the last one should be executed for both branches

It does actually! If an error handler doesn't throw an exception, the error had been handled and the promise does resolve with the return value of the handler.

Is it possible to do that?

Yes! That's one of the core properties of then, that it resolves with nested promises.

However, you could simplify your code a little bit, as you've got a bunch of duplication in there:

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


来源:https://stackoverflow.com/questions/24032318/how-to-create-a-tree-of-promises

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!