Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
736 views
in Technique[技术] by (71.8m points)

javascript - 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());
            }
        }
    });

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.

I was wondering the best away to use an async function with any of the Array.prototype functions, specifically the some function.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Alternative fancy approach:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...