El siguiente código recibe todas las recompensas canjeadas por el usuario de una API, necesito detener el ciclo para que no las complete todas a la vez.
El ciclo for recorre todas las recompensas que el usuario actual ha canjeado a través de la API de Twitch y luego las cumple si se cumplen condiciones específicas. Quiero que solo cumpla una redención, no todas (x) la cantidad de ellas.
La parte de la recompensa de cumplimiento ocurre en: cumplirRecompensa()
Para obtener un fragmento de código completo, haga clic aquí: https://pastebin.com/7k5WNhmD
// looping over reward returned data for (let i = 0; i < rewards.length; i++) { async function fulfillReward() { await fetch( `https://api.twitch.tv/helix/channel_points/custom_rewards/redemptions?broadcaster_id=58606718&reward_id=08d5e2d9-ddd7-4082-bc78-39b06b35cd68&id=${rewards[i].id}`, { method: 'PATCH', headers: { 'client-Id': process.env.TWITCHBOT_CLIENT_ID, Authorization: `Bearer ${process.env.TWITCHBOT_ACCESS_TOKEN}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ status: 'FULFILLED', }), } ) } const currentReward = rewards[i] const currentRewardUsername = currentReward.user_name.toLowerCase() if (currentRewardUsername === input.toLowerCase()) { countDocuments(discordID) .then(() => { return findOneUser(discordID) }) .then(() => { // All (x) amount of rewards get fulfilled instead of the first matching result fulfillReward() interaction.reply('success') }) .catch((err) => console.log(err)) } else if (currentRewardUsername != input.toLowerCase()) { return interaction.reply(`The Twitch user **${input}** has not redeemed the channel reward!`) } }La solución general para salir de un ciclo cuando se cumple una condición es incorporar una declaración de break en cualquier condicional que decida que el ciclo ha logrado su propósito antes de tiempo.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break
Hice un fragmento simple que ejecuta un millón de ciclos for-next ciclo pero termina después de 10 ciclos cuando se cumple una condición, usando break .
let loopNumber = 0; for (let i=0; i<1000000; i++) { loopNumber++; if (loopNumber==10) { break; } } // next i; console.log(loopNumber);No estoy seguro de haber entendido completamente lo que realmente quieres, pero intentemos:
async function fulfillReward(reward) { await fetch( `https://api.twitch.tv/helix/channel_points/custom_rewards/redemptions?broadcaster_id=58606718&reward_id=08d5e2d9-ddd7-4082-bc78-39b06b35cd68&id=${reward.id}`, { method: 'PATCH', headers: { 'client-Id': process.env.TWITCHBOT_CLIENT_ID, Authorization: `Bearer ${process.env.TWITCHBOT_ACCESS_TOKEN}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ status: 'FULFILLED', }), } ) }Si solo recibe la recompensa como un parámetro, no necesita declarar funciones dentro de for (por favor, nunca haga eso)
Entonces lo llamas enviar el parámetro de recompensa.
if (currentRewardUsername === input.toLowerCase()) { countDocuments(discordID) .then(() => { return findOneUser(discordID) }) .then(() => { fulfillReward(currentReward) interaction.reply('success') }) .catch((err) => console.log(err)) } else if (currentRewardUsername != input.toLowerCase()) { return interaction.reply(`The Twitch user **${input}** has not redeemed the channel reward!`) }Actualicé su código aquí https://pastebin.com/clone/7k5WNhmD , pero realmente no puedo probarlo, así que avíseme si necesita algo más
prueba esto.
for (let i = 0; i < rewards.length; i++) { async function fulfillReward() { await fetch( `https://api.twitch.tv/helix/channel_points/custom_rewards/redemptions?broadcaster_id=58606718&reward_id=08d5e2d9-ddd7-4082-bc78-39b06b35cd68&id=${rewards[i].id}`, { method: 'PATCH', headers: { 'client-Id': process.env.TWITCHBOT_CLIENT_ID, Authorization: `Bearer ${process.env.TWITCHBOT_ACCESS_TOKEN}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ status: 'FULFILLED', }), } ) } const currentReward = rewards[i] const currentRewardUsername = currentReward.user_name.toLowerCase() if (currentRewardUsername === input.toLowerCase()) { function doSomething() { return new Promise((resolve, reject) => { countDocuments(discordID) .then(() => { return findOneUser(discordID) }) .then(() => { // All (x) amount of rewards get fulfilled instead of the first matching result fulfillReward() interaction.reply('success') resolve(true); }) .catch((err) => console.log(err)) }) } const ret = await doSomething(); if (ret) return ; } else if (currentRewardUsername != input.toLowerCase()) { return interaction.reply(`The Twitch user **${input}** has not redeemed the channel reward!`) } }