javascript 执行非空的promise结果而忽略空结果

bn31dyow  于 2023-03-28  发布在  Java
关注(0)|答案(2)|浏览(103)

我有这样一段代码,它执行一个函数来承诺4个公共方法,公共方法有代码来返回什么,如果他们不满足一定的条件。如果其中一个结果是空的(未定义),我希望它忽略该结果,但仍然保留并执行其他结果。任何人都有一个想法,如何做到这一点或解决它?

async sendFreeGames(channels) {
        Promise.all([this.createEpicFreeGamesEmbeds(), this.createSteamFreeGamesEmbeds(), this.createEpicFreeButtons(), this.createSteamFreeButtons()]).then(
            (results) => {
                const games = [...results[0], ...results[1]];
                const buttons = [...results[2], ...results[3]];

                if (games.length === 0) return;

                for (const channel of channels) {
                    // @ts-ignore
                    const discordAxios = axios.create({
                        baseURL: 'https://discord.com/api/v10',
                        headers: { Authorization: `Bot ${process.env.DISCORD_TOKEN}` },
                    });
                    discordAxios.post(`/channels/${channel.data.id}/messages`, { embeds: games, components: [{ type: 1, components: buttons }] });
                }
            },
        );
    }
}
wlp8pajw

wlp8pajw1#

你好像在找

async sendFreeGames(channels) {
    const [epicGames, steamGames, epicButtons, steamButtons] = await Promise.all([
        this.createEpicFreeGamesEmbeds(),
        this.createSteamFreeGamesEmbeds(),
        this.createEpicFreeButtons(),
        this.createSteamFreeButtons(),
    ]);

    const games = [...epicGames ?? [], ...steamGames ?? []].filter(Boolean);
    const buttons = [...epicButtons, ...steamButtons];

    if (games.length === 0) return;

    for (const channel of channels) {
        // @ts-ignore
        const discordAxios = axios.create({
            baseURL: 'https://discord.com/api/v10',
            headers: { Authorization: `Bot ${process.env.DISCORD_TOKEN}` },
        });
        discordAxios.post(`/channels/${channel.data.id}/messages`, {
            embeds: games,
            components: [{ type: 1, components: buttons }],
        });
    }
}

根据这些函数返回的确切内容,您可能不需要?? [],也可能不需要.filter(Boolean)。您可能还需要以相同的方式处理buttons

toe95027

toe950272#

要忽略结果中的undefinednull值,您可以在解构之前提供一个默认(即空)数组

(results) => {
   const games = [...(results[0] || []), ...(results[1] || [])];
   const buttons = [...(results[2] || []), ...(results[3] || [])];

或(如果结果中有多个数组,并且希望为所有数组提供[]

(results) => {
   results = results.map(x => x || []);
   const games = [...results[0]), ...results[1]];
   const buttons = [...results[2], ...results[3]];

但实际上,如果方法返回空数组而不是undefined,则更简洁
此外,您当前定义函数的方式,即

async function foobar() {
  Promise.all([...]).then(...);
}

任何调用你的函数foobar的人

...
await foobar();
...

将继续 * 的方式之前 * 您的Promise.all()解决。
要么

function foobar() {
   return Promise.all(...).then(...);
}

async function foobar() {
   let result = await Promise.all(...);
   //process your result array 
}

相关问题