Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

212
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!