Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

216
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda