Managing multiple promises with multiple steps

I am looking to extract information from various sources. Once each dataset is obtained, I want to send it to a separate asynchronous processor such as a worker thread. After all processes are complete, I aim to combine the data and deliver it.

Here is an example:

function multiplyAndSum(a1, a2){
  ret = 0;
  for(var i = 0, l = a1.length; i < l; i++){
    ret += a1[i]*a2[i];
  }
  return ret;
}

function getProcessedData(){
  var worker1 = new Worker('recordProcessor.js');
  var worker2 = new Worker('recordprocessor.js');
  var results = null;
  worker1.onmessage(event=>{
    results=(!results)?event.results:
      multiplyAndSum(event.results, results);
  });
  worker2.onmessage(event=>{
    results=(!results)?event.results:
      multiplyAndSum(event.results, results);
  });
  var ds1 = fetch('./dataSet1.json')
    .then(rep=>resp.json())
    .then(d=>worker1.postMessage({
      'set': 1,
      'data': d
    }));
  var ds2 = fetch('./dataSet2.json')
    .then(rep=>resp.json())
    .then(d=>worker2.postMessage({
      'set': 1,
      'data': d
    }));
  // Once results is populated return results
}

I believe I should encapsulate all of this in another Promise, but I am unsure of the exact approach to take.

Answer №1

Here is an alternative approach to solve this problem:

function multiplyAndSum(a1, a2){
  let ret = 0;
  for(let i = 0, l = a1.length; i < l; i++){
    ret += a1[i]*a2[i];
  }
  return ret;
}

function getWorkerMessage(worker) {
    return new Promise((resolve, reject) => {
        worker.onmessage(event => {
            resolve(event);
        });
    });
}

function getProcessedData(){
    const worker1 = new Worker('recordProcessor.js');
    const worker2 = new Worker('recordprocessor.js');

    let p = Promise.all([
        getWorkerMessage(worker1),
        getWorkerMessage(worker2)
    ]).then([a1, a2] => {
        return multiplyAndSum(a1.results, a2.results);
    });

    // start off both workers by sending them their data
    fetch('./dataSet1.json')
      .then(rep=>resp.json())
      .then(d=>worker1.postMessage({'set': 1,'data': d}));
    fetch('./dataSet2.json')
      .then(rep=>resp.json())
      .then(d=>worker2.postMessage({'set': 1,'data': d}));

    return p;
}

// usage
getProcessedData().then(result => {
    console.log(result);
}).catch(err => {
    console.log(err);
});

Here is my interpretation of the task at hand.

  1. Create two workers
  2. Fetch two sets of data and assign one set to each worker
  3. After the workers process the data, multiply the resulting arrays and sum them to obtain a final value
  4. The final value is then returned to the caller

For a cleaner solution, I converted the worker message into a promise that resolves to the final result. Using Promise.all(), I wait for both workers to finish processing. This allows for multiplying and summing the data arrays to get the desired final result.

One potential question remains: Should the workers be cleaned up after use?

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

Validation in AngularJS - Setting minimum length for textarea using ng-minlength

I am currently tackling a project that heavily relies on AngularJS for the front-end. Here's what I am dealing with: The validation requirement I am aiming for is as follows: The Next button should remain disabled unless the reason provided is at le ...

Having trouble with implementing a 64-bit bitwise AND operation in JavaScript?

I've been attempting to perform a bitwise AND operation on long numbers using Javascript. Despite trying the solutions provided at (How to do bitwise AND in javascript on variables that are longer than 32 bit?), none of them have been accurate for the ...

Attempting to grasp the concept of Thennables within the VSCode API. Can these TypeScript code examples be considered equivalent?

I'm looking to perform a series of modifications on a document using the VSCode API. The key function in this process is Workspace.applyEdit, which gives back a Thennable. This is my first encounter with it, and the one returned from this function doe ...

Webpack has no issues building the files, however, the JavaScript fails to execute during runtime

I recently upgraded from Webpack v4 to v5, following the documentation and addressing any deprecation messages from the CLI. The build was successful, but when testing the application, I noticed that the JavaScript wasn't running and no errors were be ...

Guide to increasing a field value in Backendless.com

Below is an overview of the table structure I have: Table data ---------------------------------- - User - ---------------------------------- | objectId | name | password | ---------------------------------- | z12ttttt | ...

Incorporating a dynamic HTML editing button to every new row in a table using JavaScript

My application features a form that allows users to dynamically add new rows to a table using JavaScript: // Function to add a new account row if (tit.innerHTML === "Add Account"){ var table = document.getElementById(tableId); var row = table ...

Record collection of elements - JavaScript Angular

I am facing an issue with my page code. The code contains a list of items and I need to extract the values of Test, Application, Success, Error from these items. However, when I try to write this data to a file, it returns [object, Object]. Can someone ple ...

Display a list of items using ReactJS by mapping through an array of objects and rendering based on

How can I render a set of <div> </div> based on the items in an object without having to specify their names? In the code snippet below, I want the display of WorkObjectID and WorkObjectVal to be dynamic rather than static. If I include TempOb ...

displaying a div as a pop-up within an ASP.NET MVC 4 web application

One aspect of my asp.net MVC 4 application involves a partial view structured like so: <form class="qty-add" action="#" method="POST"> <label>Qty:</label> <div class="inp-controller"> <a href="#" c ...

The final DOM is not loading properly when using Jest and React Testing Library during page initialization

I'm currently working on testing my React application with Jest and React Testing Library. During this process, I am attempting to verify that the login page displays a specific message once it has fully loaded. Upon initial loading of the login page, ...

Guide on redirecting to a new domain using a cookie in Express.js

I am working on a web app using Express on Node and I want to add a proxy login feature that allows users to be automatically logged in and redirected to another site after logging into my site. Within my routing function, I have the following code: res ...

Begin the input box with some text

Currently, I am trying to incorporate a form field that automatically adds "http://" when clicked or typed into by a user. Below is the code snippet I have been using: <script type="text/javascript"> var input = $( "#website" ); input.val( input ...

Utilizing Express.js: A Guide to Fetching File Downloads with a POST Method

Although GET requests are successful, I am facing challenges when using POST to achieve the same results. Below are the different code snippets I have attempted: 1. app.post("/download", function (req, res) { res.download("./path"); }); 2. app.post ...

Receiving a blank string after calling fs.readFile within the chokidar.watch(path_file).on('change', ...) function

This is my current Node project setup: https://github.com/tlg-265/chokidar-issue https://i.stack.imgur.com/qYKlR.png $ git clone https://github.com/tlg-265/chokidar-issue $ cd chokidar-issue $ npm i $ npm run watch-changes The project monitors changes ...

Facing issues when attempting to link two databases using Express

Encountering an issue while attempting to use two Oracle databases simultaneously. My startup function only executes the first connection try-catch block, but displays the console log connection message of the second try-catch block without actually estab ...

Creating animated direction indicators in the "aroundMe" style with ngCordova

I am attempting to recreate a compass or arrow similar to the one featured in the AroundMe Mobile App. This arrow should accurately point towards a pin on the map based on my mobile device's position and update as I move. I have been struggling to fi ...

Using regex to confirm prices are accurate

Can anyone assist me with validating input using regEx in Vue? I'm struggling to create one and haven't been able to find the correct pattern online for what I need. The specific validation I am attempting is for a price value that should be a f ...

What is the best way to extract the text between the @ symbol and the next space using JavaScript or React?

As a beginner in programming, I am looking to extract the text following an @ symbol and preceding the next space entered by a user into an input field. For instance, consider the following input: somestring @user enters In this case, my goal is to cap ...

Since switching to PHP 5.5 from version 3.x, I have noticed that it is attempting to interpret my JavaScript comment within a script tag in a PHP include file

After a long break from working with PHP, I recently encountered an issue with an older website I built using PHP and the include function. The site was functioning perfectly until the web host updated PHP to version 5.5, causing a strange bug where it see ...

Is there something incorrect with the incrementation in JavaScript?

for (let i = 0; i < 5; ++i){ alert(i); } for (let i = 0; i < 5; i++){ alert(i); } Both of these constructs get the same result: 0, 1, 2, 3, 4. But what are the underlying differences between them? And does the choice of increment in a for l ...