【发布时间】:2017-08-05 22:59:15
【问题描述】:
我对@987654321@ 的最佳实现感兴趣,它旨在提供布尔结果。我的问题考虑了 Promises / Futures 的任何实现,其中包括 then 的逻辑等价物,如 Promises/A+。
我的问题是:这样的 Promise resolve 是否应该带有布尔值,无论结果如何,还是应该在 true 和 true 上使用 resolve 和在 false 上使用 reject?
因此在 Javascript 中就像在 ES6 中一样:
class Named {
constructor(name) {
this.name = name;
}
// always resolve
isFoo1() {
return new Promise(resolve => {
resolve(this.name === 'Foo');
});
}
// resolve or reject
isFoo2() {
return new Promise((resolve, reject) => {
if (this.name === 'Foo') {
return resolve(true);
}
reject(new Error('Not Foo!'));
});
}
}
现在你可以这样做了:
const namedObjects = [new Named('Foo'), new Named('FooBar'), new Named('Foo')];
const nameChecks = namedObjects.map(obj => obj.isFoo1());
const checkNames = () => namedObjects.map(obj => obj.isFoo2());
// using always resolve
Promise.all(nameChecks)
.then(results => {
if(results.every(v => v)) {
return alert('all is foo!');
}
alert('all is not foo!');
});
// using resolve or reject
Promise.all(checkNames())
.then(() => alert('all is foo!'))
.catch(() => alert('all is not foo!'));
我认为“解决或拒绝”版本更自然地与 Promise 概念配合使用 - 特别是使用 Bluebird 中的扩展实现。
【问题讨论】:
-
您可以使用任何适合应用程序的东西来解决 Promise。对象、数字、字符串等等。
-
请注意,两个版本都使用 bool 解析 - 问题不在于使用什么解析。但是是否映射 bool 来解决 and 拒绝或 bool。
-
对不起,这个问题仍然没有任何意义。
标签: javascript promise future boolean-logic