Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

138
Visualizações
Looping through array and update variable based on async code

I am trying to loop through an array and calling a promise, and based on that result it updates the variable. The code is working as I wanted but I am concerned if this is a good way to write it. Are there any better ways? Thank you in advance.

/**
*
* u/returns Resolves a promise and returns value 'b'
*/
async function generatePromise() {
   return Promise.resolve('b');
}

async function main() {
   let showWarning = false;
   // List of users
   const users = ['a', 'b', 'c'];
   //Looping through users array and compare the result from promise and update showWarning boolean
   await users.reduce(async (promise, user) => {
     await promise;
     const result = await generatePromise();
     if (result === user) showWarning = true;
   }, Promise.resolve())

   console.log(showWarning)
}
main();
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Seems unnecessarily complicated and the logic is somewhat backwards. Assuming that generatePromise will always return the same response, why would you call it multiple times? Call it once and check whether the value is contained in the array:

const showWarning = users.includes(await generatePromise());

If the function needs to be called multiple times (e.g. because it could potentially return a different response per input/user) then you can use a simple for loop:

for (const user of users) {
  if (user === await generatePromise()) {
    showWarning = true;
    break; // why check other users if `showWarning` won't change anymore?
  }
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda