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?
CodePudding user response:
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)
})