What is the best technique for accessing information from protractor's promises series?

My function successfully retrieves the index of an element with the text "check" and prints it using console.log:

function getIndex() {
    return element.all(by.css(".palette__item.ng-scope>span")).then(function (colorList) {
        colorList.forEach(function (elem, index) {
            elem.getText().then(function (text) {
                if (text == "check") {
                    console.log(index);
                    return index;
                }
            });
        });
    });
}

Despite numerous attempts, I have been unable to retrieve the data from it successfully. My latest approach was:

var res = null;
webDriver.promise.fullyResolved(getIndex()).then(function (index) {
    res = index;
});
console.log(res);

Even after initializing the `res` value inside the function to guarantee promise resolution, it still returns null.

I suspect an error in the `getIndex()` function, possibly related to the placement of the return operator. I am in need of assistance as I am out of ideas on how to make it work. Any help is greatly appreciated.

Answer №1

You might be overcomplicating things a bit. Instead of using the "forEach" method, consider utilizing the reduce() method:

function determineIndex() {
    return element.all(by.css(".palette__item > span")).reduce(function (accumulator, currentElement, currentIndex) {
        return currentElement.getText().then(function (text) {
            if (text == "check") {
                return currentIndex;
            } 
        });
    }, -1);
}

How to use:

determineIndex().then(function (index) {
    console.log(index);
});

Also, avoid using the ng-scope class in your locators as it is a specific Angular technical class without much significance for your locator.

Answer №2

Although I am unable to debug at the moment, the following solution may resolve the issue:

function findIndex() {
    return element
            .all(by.css(".palette__item.ng-scope>span"))
            .then((colorList) => { 
              // obtain text for all elements
              return Promise.all( colorList.map( (el) = el.getText() ) ); 
            })
            .then((colorList) => {
              // both text and index are necessary
              return colorList.map( (el, ind) => [el, ind] )
              // filter out elements with text "check"
                              .filter( (elArr) => elArr[0] == 'check' )
              // discard text and keep only the index
                              .map( (elArr) => elArr[1] );
            })
}

The main issue lies in mixing functions that return promises with other iterator-functions. This results in the loss of the promise context when the return statement is executed.

Answer №3

Here are a few points to consider:

Firstly, the variable is initialized outside of the promise but its value is assigned within the promise. While this is acceptable, the placement of the console.log() statement in your code is important. If it remains at the bottom of the code, it may run before the promise resolves, resulting in the variable 'res' being null.

Have you tried logging the value of res inside the promise?

Regarding the getIndex function, why are you using promises within the forEach loop? Have you considered restructuring the code like this:

function getIndex() {
    return element.all(by.css(".palette__item.ng-scope>span")).then(function (colorList) {
        colorList.forEach(function (elem, index) {
                var temp = elem.getText()
                if (temp == "check") {
                    console.log(index);
                    return index
            });
        });
    });
}

Based on the information provided, this is the best advice I can offer. It is important to understand the differences between asynchronous and synchronous code.

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

Discovering a method to detect clicks outside of a React functional component

Looking to identify when a click occurs outside of a React functional component. After stumbling upon an article, I followed the provided code but unfortunately, it didn't work as expected. Despite identifying the issue, I am still searching for a so ...

Receiving an error of "undefined" when trying to capture the selected

One issue I am facing is capturing the selected user option and sending that value in a post request. Let's put aside the post part since it's not directly related to the main question at hand. Currently, the value is showing up as undefined. ...

Node.js is encountering an error with the post method where req.body is returning an empty

When utilizing cURL or Postman, the operations perform as anticipated curl -d 'username=Johny Sample&title=My First Post&description=We need some assistance cleaning up after the hurricane&postID=Johny Sample_1' http://localhost: ...

Is it better to set the language of Puppeteer's Chromium browser or utilize Apify proxy?

Looking to scrape a website for French results, but the site supports multiple languages. How can I achieve this? Is it best to configure Puppeteer Crawler launch options using args, like so: const pptr = require("puppeteer"); (async () => { const b ...

How to effectively manipulate nested arrays in JavaScript without altering their references

Welcome everyone, I've been working on a project using next.js and I've encountered an issue with filtering posts. The filter function works perfectly when the posts are in a simple array like ObjChild. However, I have another section on my site ...

What are some solutions for repairing unresponsive buttons on a webpage?

My task is to troubleshoot this webpage as the buttons are not functioning correctly. Here’s a snippet of the source code: <!DOCTYPE html> <html lang="en"> <head> ... </head> <body> <div id="container" ...

Tips for seamlessly creating the animation of sketching a line

Currently, I am working on a project that involves around 40 curved lines, each containing 30 to 200 points. Despite using BufferGeometry and setDrawRange() to draw all the lines equally, only the line with over 200 points appears smooth. I attempted using ...

How to dynamically increase vote tallies with React.js

The voting system code below is functioning well, displaying results upon page load. However, I am facing an issue where each user's vote needs to be updated whenever the Get Vote Count button is clicked. In the backend, there is a PHP code snippet ...

What could be causing my inability to accurately guess people's ages?

My latest project involves developing a game where players have to guess names from images. Each game consists of 10 rounds, followed by a bonus round where participants must wager their points on guessing the age of the person in the image within a 2-year ...

Unable to locate NPM-installed modules in the local directory

I've been working on a project and I encountered an issue with locally installed modules using NPM in NodeJS on Windows 10. Despite setting up NODE_PATH, I am still getting errors when trying to require these modules. Here is the structure of my proj ...

Creating an empty input field with a predetermined default output in ReactJS

My current challenge involves navigating form data between various components in a React application. I am looking to pass data from child components to parent components and vice versa, creating a seamless flow of information. The key requirement is to ha ...

List of nested objects converted into a flat array of objects

Looking to transform a data structure from an array of objects containing objects to an objects in array setup using JavaScript/Typescript. Input: [ { "a": "Content A", "b": { "1": "Content ...

What is the method to activate map dragging in Leaflet only while the spacebar is pressed?

When using Leaflet maps, the default behavior is to drag the view around by only clicking the mouse. However, I am interested in enabling dragging with the mouse only if the spacebar is pressed as well. I would like to reserve mouse dragging without the sp ...

Using AngularJS for client side validation and Asp.net MVC for server side validation

When it comes to using Angularjs with Asp.net MVC, as a newcomer in the world of Angularjs, I am encountering some challenges integrating it with MVC. Currently, my focus is on validating a form, utilizing: 1. For client-side: Angularjs 2. For server-sid ...

Delivering resources through the Nuxt configuration file

https://i.stack.imgur.com/2OWdE.png I came across a bootstrap template online that I want to customize for my Nuxt project. I have stored all the bootstrap files in the static folder. Within the nuxt.config.js file: module.exports = { /* ** Headers ...

FilterTextBoxExtender in AJAX enables the input of carriage returns

I need assistance with a multi-line text box that I'm using an AJAX FilteredTextBoxExtender on to restrict user input to just numbers. However, I also want users to be able to add a new line by pressing the enter key. I've looked around for a sol ...

The button is converting my text to a string instead of the integer format that I require

Hello everyone, I've been grappling with this button conundrum for the last 45 minutes, and I can't seem to find a solution. I have created three different buttons in my code snippet below. (html) <div class="action"> ...

The Dockerfile for Next13 is unable to locate the server.js file

When using the official Dockerfile from Next with the examples provided, I encounter an error while trying to build the app using a Dockerfile and docker-compose. b78-client-1 | node:internal/modules/cjs/loader:1078 b78-client-1 | throw err; b78-client ...

The specific module 'franc' does not have the export named 'default' as requested

Every time I attempt to use the franc package, I encounter the following error message: "The requested module 'franc' does not provide an export named 'default'." Unfortunately, I am unsure of what this means, despite trying to resolve ...

What is the best approach to generate and organize 100 random numbers in a program, ensuring they are sorted in ascending order from 1 to 100?

I have successfully implemented the sorting and printout functionality of the program. However, I am now facing a challenge in generating 100 random numbers between 1 and 100, sorting them. I have created an array to store the generated numbers, and I ha ...