先将数组转化为Promises数组,然后对其调用Promise.all,检查结果数组的.some是否为真。如果需要,您可以通过检查 Promise 数组中的 .some 是否是真实的非 Promise 来避免等待整个 Promise 数组解析:
cpermisPromises = command.permissions.map(permissionsKey => {
switch (permissionsKey) {
case "all":
{
return true;
}
case "OWNER":
{
return msg.roomContext.isRoomOwnerId(msg.getStaticUserUID());
}
default:
{
return config.users_groups[permissionsKey].includes(msg.getStaticUserUID());
}
}
});
if (cpermisPromises.some(result => result && typeof result.then !== 'function')) {
// at least one was truthy, don't need to wait for async call to complete
} else {
Promise.all(cpermisPromises).then((results) => {
if (results.some(result => result)) {
// at least one was truthy
}
});
}
Promise.all 可以接受包含 any 值的数组,但会在 Promise.all 解析之前等待所有 Promise 值解析。
这是一种替代方法,可让您在运行 Promises 之前检查任何同步值是否为真:
let found = false;
const promFns = [];
forloop:
for (let i = 0; i < command.permissions.length; i++) {
const permissionsKey = command.permissions[i];
switch (permissionsKey) {
case "all":
found = true;
break forloop;
case "OWNER":
proms.push(() => msg.roomContext.isRoomOwnerId(msg.getStaticUserUID()));
break;
default:
if (config.users_groups[permissionsKey].includes(msg.getStaticUserUID())) {
found = true;
break forloop;
}
}
}
if (found) {
// done, at least one truthy value was found synchronously
} else {
// need to run promises
Promise.all(
promFns.map(fn => fn())
)
.then((results) => {
if (results.some(result => result)) {
// done, at least one truthy value was found asynchronously
} else {
// no truthy value was found
}
});
}
或者,如果想要串行发送请求,这可能会导致整体请求较少,但需要更长的时间才能完成,请将 Promise.all 替换为:
let foundProm = false;
for (const fn of promFns) {
if (await fn()) {
foundProm = true;
break;
}
}
if (foundProm) {
// done, at least one truthy value was found synchronously
}else {
// no truthy value was found
}