【发布时间】:2014-11-30 01:00:19
【问题描述】:
据我了解,Promises 的主要卖点之一是能够编写扁平代码(或者,比回调地狱更扁平)。
虽然看起来在很多情况下我们需要嵌套 Promise 才能使用闭包。例如(来自q 的文档,虽然我使用的是 Bluebird):
function authenticate() {
return getUsername()
.then(function (username) {
return getUser(username);
})
// chained because we will not need the user name in the next event
.then(function (user) {
return getPassword()
// nested because we need both user and password next
.then(function (password) {
if (user.passwordHash !== hash(password)) {
throw new Error("Can't authenticate");
}
});
});
}
有没有更简洁的方法来做到这一点,而不用嵌套?
编辑:我已经设法使用.all 清理了这个特定示例,但是我认为在更复杂的情况下无法完成:
function authenticate() {
return Promise.all([
getUsername().then(getUser),
getPassword()
]).spread(function (user, password) {
if (user.passwordHash !== hash(password)) {
throw new Error('Can\'t authenticate');
}
});
}
【问题讨论】:
-
是的,但它并没有摆脱嵌套
-
有时 promise 不需要嵌套,有时则不需要。这真的取决于情况的细节。如果您正在对操作进行排序,则不必仅仅为了共享结果而嵌套。您可以将值分配给公共父闭包中可用的东西,也可以这样做,然后不必嵌套。
-
没有。消除所谓的回调地狱只是使用 Promises 的原因之一,IMO 不太重要。如果您考虑一下,回调仍然存在,它们只是包装在一些承诺库中。
标签: javascript promise q bluebird