Can anyone provide guidance on how to calculate the total sum of a JavaScript array within an asynchronous function?

Currently, I am working with Angularjs Protractor for end-to-end testing and faced an issue while trying to calculate the sum of values in a column. Although I am able to print out each value within the loop successfully, I am struggling to figure out how to add them all together. Whenever I attempt to return the total after the loop, it turns out to be undefined.

function getTotal() {
  ptor.findElements(protractor.By.className('col33')).then(function(promColCells) {
    var total;
    for (var i = 2; i < promColCells.length; i += 2) {
      promColCells[i].getText().then(function(promCellString) {
        total += parseFloat(promCellString);
      });
    }
    return total;
  });
};

Answer №1

The previous response (now removed) presented a good approach but with bulky and inaccurate promise code. Utilizing $q.all (equivalent to Promise.all in ES6-compliant promise implementations) is how we can effectively wait for an array of promises to finish:

function calculateTotal() {
    // this is where we continue
    return driver.findElements(webdriver.By.className('col33')).then(function(elements) {
        // waiting for all elements  
        return $q.all(elements.map(function(element){ return element.getText()}));
    }).then(function(elementTexts){
        return elementTexts.reduce(function(a,b){ return a + Number(b);},0);
    });
}

Alternatively, if you're not a fan of Array#reduce, you can sum using a for loop.

To use this function, it would look something like this:

calculateTotal().then(function(total){
    alert(total); // total value will be accessible here
});

Keep in mind, using an external promise library such as Bluebird allows you to write:

return Promise.cast(driver.findElements(webdriver.By.className('col33')))
    .map(function(element){ return element.getText(); })
    .reduce(function(a,b){ return a+Number(b); });

This results in a cleaner code structure.

Answer №2

Protractor comes with a built-in map function.

Here is a suggestion on how you can use it:

function calculateTotal() {
  // This is similar to using element.all(by.css('.col33')). It will return
  // a promise that resolves to an array of strings.
  return $$('.col33').map(function(cell) {
    return cell.getText();
  }).
  then(function(values) {
     // Values is an Array.<string>. Parse the integers and return the sum.
     var result = 0;
     values.forEach(function(val) {
       result += parseInt(val, 10);
     });
     return result;
  });
};

calculateTotal.then(function(total) {
});

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

The .value property on the form group displays numeric values as either null or an empty string

I'm encountering an issue with extracting data from a form group. Within my code, there is a formGroup named lineitemForm, and I am attempting to structure this form group as follows: private formatTransferData() { const depositDates = this.get ...

Is there a way to adjust user privileges within a MenuItem?

One of my tasks is to set a default value based on the previous selection in the Userlevel dropdown. The value will be determined by the Username selected, and I need to dynamically update the default value label accordingly. For example, if "dev_sams" is ...

include the ReactToastify.css file in your project using the import statement

Error in file path C:\Users\User\Documents\GitHub\zampliasurveys_frontend\node_modules\react-toastify\dist\ReactToastify.css:1 ({"Object.":function(module,exports,require,__dirname,__filename,jest){:ro ...

Node.js route does not support io.sockets.on functionality

Incorporating io.sockets.on into a route within a Node.js and Express application is proving to be challenging. I have been following the guidance provided here: While I am able to successfully send io.sockets.emit events, I am encountering an issue with ...

Guide to adding Angular 2 components to various locations in the DOM of a vanilla JavaScript webpage

Scenario: A customer is interested in creating a library of Angular 2 components that offer a technology-agnostic interface to developers. This allows developers to use plain JavaScript without needing knowledge of the internal workings of the library. Th ...

What are the steps to secure an API endpoint using PassportJS?

Within my app, I have integrated Express and AngularJS for functionality. Specifically, I am utilizing express to manage the basic web serving of the angular code through static routes. The angular code interacts with services that connect to API endpoin ...

Error encountered while attempting to define a method in a class component in React.js

Can you tell me if these two code snippets are equivalent? async onSearchSubmit(term) { const response = await axios.get('https://api.somewebsite.com/search/photos', { params: {query: term}, headers:{ ...

Exploring the power of Angular 2 Directive scopes

When it comes to Angular2, Directives do not come with "scopes", unlike Components. However, in my specific case, I require a Directive to establish a scope. Take a look at my App component - it contains an HTML template, and the foo directive could potent ...

Ways to retrieve a list of identifiers from arrays at both initial and subsequent levels

I'm currently dealing with a JSON/JavaScript structure that looks like this: { "comments": [ { "id": 1, "content": "lorem ipsum", "answers": [] }, { "id" ...

Establish a field alias with boundaries in AngularJS

I am currently working with a JavaScript object and attempting to display and edit its properties using templates. Here is a simple example: <div ng-init="friends = [ {name:'John', age:25, gender:'boy'}, {nam ...

What is the best way to organize properties within the Class Variance Authority?

Can the following be achieved in CVA? const mathPanelVariants = cva( 'relative mt-[100px] w-full rounded-sm border-l-[3px] px-[24px] py-[16px]', { variants: { variant: { theorem: { box: 'border-l-[#617bff] dark:bg-[#182 ...

Experiencing a problem with the JavaScript loading function

An error was logged in the console SyntaxError: unterminated string literal A piece of code is supposed to display a notification $(document).ready(function () { alertify.success("Success log message"); return false; }); Despite testing the cod ...

Avoiding JavaScript onclick event using JSON information

Here's a situation I'm dealing with: I have a button created using PHP that triggers a JavaScript onclick event: <button onClick='edit(this, "<?php echo $this->result[$i]["type"]; ?>","<?php echo $quality; ?>", "<?php e ...

Refresh the page before the conclusion of the express-Node js function

I am encountering an issue with a function that functions properly with small files but fails when dealing with large files. The problem occurs when the axios post request in Express JS ends, causing a page refresh. I am using React JS on the client side a ...

What is the most effective method for obtaining only the "steamid" from an AJAX request (or any other method)?

I have been attempting to extract only the "steamid" from an AJAX link without success. Could someone please provide some assistance? Here is the link to find and retrieve only the "steamid": here This is the code I have tried: var xhttp = new XMLHt ...

What could be causing the issue with npm install packages not functioning properly?

Currently, I am in the process of setting up and deploying a particular git repository locally: https://github.com/maxie112/gatsby-ecommerce-theme I am strictly adhering to the instructions provided for Mac OS. Here are the encountered error logs; maxden ...

Guide to modifying Button on fetch response in React Native

After receiving a response from the server, I need to adjust the button based on the friends_status field in the following response: { "responseHeader": { "type": "314", "status": "200", "message": "Successfully found the profile" }, "ne ...

AngularJS integration with Bootstrap Confirmation jQuery plugin

I am currently struggling to implement the Bootstrap-Confirmation plugin with AngularJS. Despite following instructions from this YouTube tutorial, I cannot seem to get the directive to function correctly. A related query on Stack Overflow references a di ...

Setting the height of a div tag in CSS/HTML5 to match the current height of the browser window

Is there a way to make the height of my div tag always equal to the height of the browser's window, so it adjusts automatically when the browser is resized? I have tried using .class { height: 100%; } But this doesn't work. I've learne ...

Trigger animation when the scroll position reaches 0.52 in Next.js using framer-motion

I’m working on a landing page and I have a section where I’d like to create a simple opacity animation using framer-motion. The issue is that these animations typically trigger as soon as you land on the page, but I want them to be based on scroll pos ...