gpt4 book ai didi

javascript - 如何创建一棵 promise 树?

转载 作者:行者123 更新时间:2023-11-28 01:14:16 26 4
gpt4 key购买 nike

我正在尝试在 Ember 中创建一棵 promise 树。

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

我想执行所示的 promise 。提到还有嵌套的 Promise createRecord(..).save().then。可以这样做吗?

这里并不完全是一棵 promise 树,因为最后一个应该为两个分支执行。如果我把它们放在一个自己的函数中,当然可以。像这样:

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

最佳答案

the last one should be executed for both branches

确实如此!如果错误处理程序没有抛出异常,则错误已被处理,并且 Promise 确实使用处理程序的返回值进行解析。

Is it possible to do that?

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

但是,您可以稍微简化一下代码,因为其中有很多重复内容:

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

关于javascript - 如何创建一棵 promise 树?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24032318/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com