Is there a way to retrieve a value following the execution of an asynchronous function loop?

I am attempting to iterate through a series of asynchronous functions and calculate the total sum of all elements, while also being able to access the final sum.

it("Practice with Select.all", function(){
    element.all(by.css('.items li')).then(function(items) {
        var len = items.length;
        var sum = "";
        for(var counter = 0; counter<len;counter++){
            items[counter].getText().then(function(item){
                sum += item;
                console.log(sum);
            });
        }
    });
});

Answer №1

If you're looking for a handy function that can do the job efficiently, check out the reduce() method:

element.all(by.css('.items li')).reduce(function(acc, elem) {
    return elem.getText().then(function(text) {
        return acc + parseInt(text);
    });
}, 0).then(function (value) {
    console.log(value);
});

Answer №2

Seems like you're working with strings when attempting to perform addition. Here's a suggested solution:

it("Practice for Select.all", function(){
    element.all(by.css('.items li')).then(function(items) {
        var length = items.length;
        var total = 0;
        for(var count = 0; count<length;count++){
            items[count].getText().then(function(item){
                total += parseInt(item);
                console.log(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

What is the best way to conceal a modal using jquery?

Click button to open modal: <button type="button" class="btn" onclick="CountClass()" runat="server" data-toggle="modal" data-target="#inlineForm1">OPEN</button> The modal code: <div class="modal fade text-left" id="inlineForm1" tabindex=" ...

Navigating through inputs using WebDriver/Selenium without specifying a target object to receive the keystrokes

Having difficulty switching to a popup window that is built within a webpage? An easy workaround for this issue is simply hitting the "enter" key. However, when it comes to using the Sendkeys.Keys("<insert Key>"); command in Selenium or the Windows n ...

The JavaScript code that functions properly in Codepen is not functioning on my HTML page

Can you help me understand why this code is working fine in CodePen, but not on my HTML page? I'm unable to identify the error that may have occurred. Any assistance would be greatly appreciated! I suspect there's an issue with connecting some jQ ...

Creating a versatile Express Router that can serve multiple websites by utilizing conditional routes based on the domain name

Instead of suggesting changes to my application architecture, I am seeking practical solutions for my specific requirements. I have code that serves different static files based on the domain name, allowing me to run multiple static HTML sites from the sam ...

Scrolling vertically at regular intervals of 5 seconds

I am experimenting with creating a vertical scrolling animation. Within a div, I have 9 elements with overflow hidden, allowing only 3 elements to be visible at once. Every 5 seconds, I aim to add styles to the elements using negative margin-top values a ...

Vue 3's "<Component :is="">" feature magically transforms camelCase into lowercase

Within my application, I have implemented a feature where users can customize the appearance of social media links on their page by defining which platforms they want to include. Each social media platform is represented by its own component responsible fo ...

Getting query parameter with hyphen in nextJS 13 - step by step tutorial

One of the challenges I am facing involves accessing a query parameter with a hyphen in its name within a route: /?previous-page=building-details Within my Page component: import EnergyEfficiency from "@/ui/energy-check/energy-efficiency" cons ...

Tips for extracting an integer from a chosen input value

New to AngularJS and trying to extract an integer from select options. Here is the setup: <select class="form-control" id="decimation" placeholder="1 or 8" ng-model="data.settings.decimation"> <option type="number" value="1" ...

Showing content based on the route - Angular

I'm struggling to hide the navbar based on a specific route in my application. I have managed to subscribe to the route changes, but I am having difficulty changing the display property accordingly. Here is what I have so far: export class AppCompo ...

Add a close event to a list item in JQuery before

When I click on "+ List Item" or press enter in the input box, I want to add a new list item with a checkbox, input box, and a close button. The functionality should be similar to Google Keep's checked item event working in notes. Currently, the code ...

TypeError: Unable to access the 'items' property of a null value

I am currently working on a program and I am facing an issue where I need to access something from the first component in the second component. Can anyone provide assistance on how to properly construct this? Below is a snippet of my code: ...

Transferring Session ID between Express.js and Socket.io while dealing with iframes from distinct origins

My Node application built with Express.js and Socket.io is facing an issue where they are not sharing the same session ID when running under iframe with different origins. When accessed directly or through iframes with the same origin, everything works fin ...

Launching a Vue Cli 3.10.0 project on a designated port

Is there a way to consistently serve a Vue CLI project on a specific port, like 8888? I've tried various methods without success. Adjusting the serve script in package.json to include the flag --port 8888 Updating the devServer option in vue.config. ...

Once you've made the switch to .mjs files, make sure to replace all

I recently made the switch from using a js file to an mjs file, as I heard this is now the standard practice. However, I am encountering a beginner's issue. In my mongoose.js file, I had the following code: const mongoose = require('mongoose&apos ...

Use JavaScript to dynamically add CSS styles to elements before and after a button wrapper

My code seems simple, but for some reason it's not working. I'm trying to add CSS styles to a button when there is a div with the class .wp-block-group both before and after the button. $(".btn-superimposed-wrapper").each(function () ...

Fetching an image from a URL using Node.js

My problem lies in downloading images with unknown file extensions (such as jpg, png, jpeg, or bmp) from a URL. I want to check the Content-Length of the image and if it is greater than 0, download it to a file. If not, I want to try downloading the image ...

Preventing browser flickering when using 'loadURL' to switch between URLs in Electron

Within my electron app, I am utilizing a singular window. As users navigate through the various "forms" within the application, I make use of the mainWindow.loadURL('file://...') function. Unfortunately, this approach leads to a flashing effect w ...

Replace the anchor tags with a JavaScript array

Looking to replace a simple anchor link with JavaScript array code. We're taking the long route here, and it's not as straightforward as we thought. The scrollTo property isn't working for us; can anyone spot where we might be going wrong? ...

Deciphering the AJAX Response

I just want to express my gratitude to anyone who assists me. However, I am facing issues in parsing my AJAX response correctly: Here is my AJAX Request: $('#sumbit_LoggingGet').on 'click', -> username = $('#login_username&apo ...

What is the best way to retrieve the input value using jQuery?

I am using a serializer to pass json values into this input field. How can I access the dynamic values? Currently, it is only returning "[" instead of the json values. <input id="jsonValue" type="hidden" value="<%=sb.ToString%>"/> $('#j ...