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

213
Visualizações
Best approach to using async functions on array of values?

I have a question about the best approach to calling async functions on an array of values, in JavaScript.

Please note that in my environment I am not able to use any async/await methods, nor can I use promises.

For example, in my case, I have this SHA256 encryption function:

sha256(not_encrypted_string, function(encrypted_string) {
  // do stuff
});

I want to use this function to encrypt every value in an array of unknown length:

const strings_i_want_to_hash = ["string1", "string2", "string3", "string4", "string5", ...];

So my question is, what is the best way to approach hashing all of these? I can't use something like

const hashed_strings = strings_i_want_to_hash.map(sha256);

...because it's async. Right?

The best way I can think of, is to create an empty array to put the hashed strings in, and wait for that to be as long as the input array:

const hashed_strings = [];

strings_i_want_to_hash.forEach(function(str){
  sha256(str, function(hashed_str) {
    hashed_strings.push(hashed_str);
  });
});

while (hashed_strings.length < strings_i_want_to_hash.length) {
  continue;
}

...but this seems like a really shitty approach.

Do you guys know of a better way to handle this?

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

0

While I haven't tried your code, I suspect that the while loop will be blocking the thread and your program may never complete.

One option is to wrap your async function in another that tracks the count. Something like:

function hashString(str, cb){
    // Simulate async op
    setTimeout(() => cb('hashed-'+str), 500);
}

function hashManyStrings(strings, cb){
    const res = [];
    strings.forEach(function(str){
        hashString(str, function(hashed){
            res.push(hashed);
            if(res.length === strings.length){
                cb(res);
            }
        })
    })
}

hashManyStrings(['hi', 'hello','much', 'wow'], function(result){
    console.log('done', result)
}) 

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