如何将Array.prototype.some()与异步函数一起使用? [英] How to use Array.prototype.some() with an async function?
问题描述
我正在尝试执行以下操作:
I am trying to do the following:
command.permissions.some(async permissionsKey => {
switch (permissionsKey) {
case "all": {
return true;
}
case "OWNER": {
return await msg.roomContext.isRoomOwnerId(msg.getStaticUserUID());
}
default: {
return config.users_groups[permissionsKey].includes(msg.getStaticUserUID());
}
}
});
但是它始终是正确的,因为Array.prototype.some不期望异步函数,因此在调用该函数时会返回一个promise.一个承诺是真实的.
However it always is true because Array.prototype.some does not expect an async function so a promise is returned when the function is called. A Promise is truthy.
我想知道将异步函数与Array.prototype函数(尤其是some函数)一起使用的最佳途径.
I was wondering the best away to use an async function with any of the Array.prototype functions, specifically the some function.
推荐答案
如果您希望在第一个承诺通过true
解析后立即得到结果,您也可以这样做:
If you want the result as soon as the first promise resolves with true
, you can do that too:
const somePromise = promises =>
new Promise((resolve, reject) => {
let resolveCount = 0;
const resolved = value => {
if (value) {
resolve(true);
} else if (++resolveCount === promises.length) {
resolve(false);
}
};
for (const promise of promises) {
promise.then(resolved, reject);
}
});
其他花哨的方法:
const never = new Promise(() => {});
const somePromise = promises => Promise.race([
Promise.race(promises.map(async p => !!await p || never)),
Promise.all(promises).then(r => r.some(Boolean)),
]);
不过,在您的特定情况下,由于最多只有一个承诺,因此有更好的方法来实现:
In your specific case, though, since there’s at most one promise, there’s a much better way to do it:
let hasPermission =
command.permissions.some(permissionsKey => {
switch (permissionsKey) {
case "all":
return true;
case "OWNER":
return false;
default:
return config.users_groups[permissionsKey].includes(msg.getStaticUserUID());
}
});
if (!hasPermission && command.permissions.includes("OWNER")) {
hasPermission = await msg.roomContext.isRoomOwnerId(msg.getStaticUserUID());
}
这篇关于如何将Array.prototype.some()与异步函数一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!