What is the most effective method for utilizing async functions with an array of values?

Seeking advice on the most efficient method for calling async functions on an array of values in JavaScript.

It's important to note that my current environment does not support the use of async/await methods or promises.

For instance, I have a SHA256 encryption function like this:

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

The goal is to encrypt all values in an array of unspecified length:

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

So the question at hand is: what is the most effective way to hash all these values without using something like

const hashed_strings = strings_i_want_to_hash.map(sha256);

...since it involves asynchronous operations. Correct?

One approach could be to create an empty array to store the hashed strings and wait until it matches the length of 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;
}

However, this method seems quite inefficient. Are there better alternatives to handle this task?

Answer №1

Although I haven't personally tested your code, it seems likely that the while loop could potentially cause the thread to block, preventing your program from ever finishing.

One approach to avoid this issue is to encapsulate your async function within another function that keeps track of the count. You can try something like this:

function hashString(str, cb){
    // Simulating async operation
    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)
}) 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Setting up the initial 3 parameters in a v-for loop

What is the best way to begin a v-for loop? For instance, we have an array named "array" with the following values: array = [dog, cat, e, f, g]; I am interested in using a v-for loop that will start looping through and only consider the first 3 values. ...

Steps for updating inputs using a modal selection

I am currently utilizing the Laravel Framework and facing an issue where I need to allow users to choose a specific event to edit if they have multiple event records. I have already implemented a modal that displays all the events, but I am unsure how to c ...

Is there a way to prevent Prettier from automatically inserting parentheses for a single argument in an arrow function?

Currently, I've integrated Prettier into my workflow, but I've encountered an issue with arrow functions in JavaScript. For example: arg => console.log(arg) However, Prettier automatically formats it as: (arg) => console.log(arg) This for ...

struggling to incorporate API Json response data into my HTML file using AngularJS

Below is the code I am currently using: angular.module('ngApp', []) .factory('authInterceptor', authInterceptor) .constant('API', 'http://myserver.com/app/api') .controller('task', taskData) function task ...

Issue with VueJS instance: Unable to prevent default behavior of an event

Is there a way to disable form submission when the enter key is pressed? Take a look at the different methods I've attempted along with the code and demo example provided below. SEE PROBLEM DEMO HERE Intended outcome: When you focus on the input, pr ...

Do back-end routes get activated when the route path in the URL matches, or when a fetch request is initiated from the front-end?

Exploring the contrast between utilizing a fetch API versus directly visiting the URL corresponding to the route path. Consider a backend route structured as follows: let ALL_RESTAURANTS = [ { id: "0b65fe74-03a9-4b37-ab09-1c8d23189273", name: ...

Following the object's update, the program is incapable of executing the compareTo function

I am currently working on adjusting the product placement within the print menu. After updating some information about the products, I need to sort them by "Quantity" in descending order. In cases where the quantities are the same, the list should be sorte ...

Communicating with Socket.io using the emit function in a separate Node.js module

I've been trying to make this work for the past day, but I could really use some assistance as I haven't had much luck figuring it out on my own. App Objective: My application is designed to take a user's username and password, initiate a m ...

Why isn't my onClick event functioning as expected?

I used the handleClick function in an onClick event, but it's showing an error (this is not defined). var Buttons = React.createClass({ getInitialState() { return { field: ':P ' } }, handleClick(field ...

Trouble accessing properties in Mongoose objects?

I am facing a puzzling issue while attempting to retrieve properties from a MongoDB (mongoose) find query. When I log the entire object, everything is visible. However, when I attempt to access a specific property, it returns undefined. The object is cert ...

Disable automatic focusing for a material-ui popover component

I am struggling to create a search match list that updates as the user types in their query. However, I am facing an issue where the input element loses focus to the pop-up. I have attempted to programmatically set the focus using refs, but I am unable to ...

Storing two values when an option is selected in a dropdown in Javascript using the map functionIn this tutorial,

The JSON data provided is structured as follows: [ { "course_name": "React", "course_id": 2 }, { "course_name": "Python", "course_id": 1 } ] Displa ...

Tips for displaying the response next to the corresponding table data (td) cell

When I click the fourth button, the response is showing on the first td. I want to show the response next to the respective td. Below is my code, can someone help me? Thanks. (i.e., here I am getting the $status using a query, but I want this status to di ...

Storing data in Angular service for future use

My ui-grid is functioning correctly, utilizing server side pagination with a view button to display row details on a separate page. However, upon returning to the grid after viewing details, it defaults back to displaying the first page. I would like it to ...

Issues with Fetch API and CORS in Web Browsers

Hello, I'm encountering an issue related to CORS and the Fetch API when using browsers. Currently, my setup involves running a NodeJS server built with Express on localhost:5000. This server responds to a GET request made to the URL /get_a, serving ...

Maintaining a consistent distance from the baseline while adjusting the font size dynamically in an HTML text element

Looking to lock a text element to the baseline while also resizing its font dynamically when the window is resized. I created a demonstration on jsfiddle. However, the issue arises when the window size changes; the distance from the bottom of the window i ...

Are the barcodes accurate or inaccurate?

Start by calculating the total of the numbers in the odd positions (the first, third, …, eleventh positions) and then multiply this sum by 3. Next, calculate the sum of the numbers in the even positions (the second, fourth, ...

Python Function to Find the Most Frequently Occurring Element

I am currently working on developing a function that can accurately determine the most frequent element in an array that it is provided with. The current implementation of my code is as follows: def get_classification(classes): from collections import ...

Navigate to the middle of a DIV container in Angular 7

Is there a way to programmatically scroll to the center of my element on both the Y and X axes when a specific function is executed? My HTML structure includes the following (I am aiming to scroll to the middle of #viewport): </div> <div # ...

Node.js callback functions are a crucial part of the program's operation. It can be frustrating when a TypeError occurs, such as when trying

Currently, I am grappling with the concept of callbacks. Can someone clarify why I am facing difficulties updating my webpage using the callback from setInterval? Upon running the code, I encounter the following error: /home/pi/Programming/RC Car/server_ ...