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

89
Visualizações
Asynchronous finding highest number

im looking for a way to asynchronous iterate over an array and update a variable and in the end return this variable.

export const test = async(
...
): Promise<number> => {
let highestAmount = 0;
    for (const entry of entries) {
        const check = async () => {
            let amount = 0
            try {
                newAmount = await getAmount(entry);
            } catch (e) {
                return;
            }
            if (newAmount > amount ) {
                highestAmount = newAmount;
           }
        }
        check()
    }
    return highestAmount;
}

In this current state i only get 0's back because the function doesnt wait for its finish. Is there a way that the function only returns if all processes inside the for are finished ? Lets say the getAmount(entry) function takes 1 second to finish then i have to wait around entries.length seconds. Im trying to find a way to execute this in 1 second so getAmount is called for every entry asynchronously => function returns highest number

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Lets say the getAmount(entry) function takes 1 second to finish then i have to wait around entries.length seconds. I'm trying to find a way to execute this in 1 second

If you have five calls that take one second you can't execute and return a value from the function in one second.

Is there a way that the function only returns if all processes inside the for are finished?

Yes. This, however, is possible.

If you map over your array to produce an array of promises that you can await with Promise.all, you can then use Math.max to get the highest number from that array.

// Generate a random number
function rnd() {
  return Math.floor(Math.random() * (100 - 0) + 0);
}

// Mock API call which returns the number passed into
// multiplied by an erratic method of
// creating a new random number
function getAmount(el) {
  return new Promise(res => {
    setTimeout(() => res((el - rnd()) + rnd()), 500);
  });
}

// Create an array of promises, await them to resolve
// and then return the highest number
async function getHighest(entries) {
  const promises = entries.map(el => getAmount(el));
  const data = await Promise.all(promises);
  console.log(data);
  return Math.max(...data);
}

// Await the promise that `getData` returns
// and log the result
async function main(entries) {
  console.log(await getHighest(entries));
}

const entries = [1, 2, 3, 4, 5];

main(entries);

about 4 years ago · Juan Pablo Isaza Relatório

0

There are a couple of things missing to make this wait:

  1. Put an async in the parent function
  2. Put an await in the check function call

For example:

export const test = async (
...
): Promise<number> => {
  //...
  await check();
};

There might also be ways to make these async calls run in parallel.

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