如何创建一个承诺树

How to create a tree of promises?

本文关键字:一个承诺 创建 何创建      更新时间:2023-09-26

我正在尝试在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));

我想执行如下所示的承诺。提到还有嵌套的承诺createRecord(..).save().then。这可能吗?

这里并不是一个承诺树,因为最后一个应该在两个分支中执行。当然,如果我把它们放到一个单独的函数中。像这样:

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

最后一个应该在两个分支中执行

确实有!如果错误处理程序没有throw异常,则错误已被处理,并且承诺确实通过处理程序的return值解决。

这可能吗?

是的!这是then的核心属性之一,它通过嵌套的承诺来解决。

但是,你可以稍微简化一下你的代码,因为你有很多重复的地方:

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