Tips for ensuring element.all().each() resolves before continuing execution

I am currently attempting to loop through a list of elements in order to locate any one of them that has a specific value as its getText() result.

The issue I am encountering is that my test is not following the sequence I have outlined.

I have researched queuing and Promise resolution extensively, but I am unsure of how it impacts my current situation.

This is what I am trying to accomplish:

it('should search for applications by name', function() {
    var exists = false;

    element.all(by.repeater('item in list')).each(function(elem) {
        elem.getText().then(function(text) {
            if(text === 'foo') 
                exists = true;
            return exists;
        }).then(function(exists) {
            console.log('current value: ' + exists);  // This displays later
        });
    });

    console.log('final result: ' + exists);   // This appears first in the console
})

Any advice on how I can ensure the boolean value I desire is determined prior to being logged at the conclusion would be greatly appreciated.

Answer №1

Protractor operates asynchronously, using promises and controlled by a Control Flow:

The APIs of WebDriverJS (and consequently Protractor) are completely asynchronous. Every function returns promises.

WebDriverJS manages a queue of pending promises known as the control flow to maintain organized execution.

In simpler terms, do not expect the code to execute from top to bottom.

If you require a single boolean value indicating the existence of a specific element, avoid using each() as it simply applies a function to each element. Instead, utilize reduce():

var exists = element.all(by.repeater("item in list")).reduce(function(acc, elem) {
    return elem.getText().then(function(text) {
        return !acc ? text === 'foo' : acc;
    });
}, false);

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 JQuery autocomplete feature is providing a data array with labels and values, however, it is not displaying the labels as suggestions

Currently, I am implementing an AJAX call using Jquery-autocomplete on a WordPress website. The call returns a list of airports with their corresponding Airport ID as the value. However, I am encountering an issue where the input is not displaying anythin ...

Uncertain on the functionality of OnSubmit

I am currently working with the following code: <form onSubmit= {handleSubmit}> <div className="form-group"> <label htmlFor="focusedInput">Level</label> <input className="form-control" id="focusedInput" typ ...

Retrieving data from controllers and passing it to directives in Angular applications

I have integrated a directive into my Angular website to generate a customized page header. Within this header, I aim to display the user's first and last name. My application is enclosed within a MainController. Below is the rendered HTML: <html ...

Is it possible to modify the state of a function component from a different function in React?

React 16.8 introduced the state and setState features to function-based components. Here's my query: If we have a Function based component, is there any way to modify its state from outside the function? For instance: import {useState} from &apos ...

Switching from react-scripts to vite causing unexpected jsx issues

I am facing challenges with migrating from react-scripts to vite. My project is structured using .js files instead of JSX, but I keep encountering errors such as: [vite] Internal server error: Failed to parse source for import analysis because the content ...

Collecting all Material-UI components into a single document

Currently, I am engaged in a Meteor project that utilizes Material UI and ReactJS. I wish to streamline the process by creating a single file that imports all necessary Material UI components for my project. This way, instead of adding individual exports ...

Alerts are essential for the proper functioning of the AJAX function. Without them

As I incorporate a substantial amount of AJAX with XML Http Requests on my website, I encounter a peculiar issue with a few random AJAX calls. There seems to be an execution problem within my JavaScript code in the onreadystatechange function where certain ...

User input can be masked with jQuery to accept two distinct formats

I need help creating an input mask that requires two different values from the user. I want the final input to look like this: [X.XXX$ for X years] Is it possible to achieve this using the jQuery Plugin inputmask? I've attempted with the code snippe ...

Creating a dynamic form in Javascript/Jquery to automatically calculate values entered into

Recently, I came across a jQuery code snippet that allows for the creation of dynamic textboxes. Let me share the jQuery code with you: var rowNum = 0; function addRow(frm) { rowNum ++; var row = '<p id="rowNum'+rowNum+'" ...

Neglecting to pass data to the controller through the onclick function

Using this specific button element in my JavaScript implementation has raised some concerns. <button id="bid" type="button" class="button" onclick="connect()">Save</button> While I have noticed that it displays an alert message when 'ale ...

How can we stop the page from scrolling after a click?

Upon clicking the link labeled Click Me, the page automatically scrolls back to the top. This behavior is not desired. How can I correct this issue? For example, here is a link to a relevant resource: http://jsfiddle.net/Y6Y3Z/ Regarding the scroll-bar: ...

Selenium's enigmatic 1-minute pause in offline mode

Conditions: To successfully execute offline mode automation, Chrome browser must be used as specified in this guide An operational online/offline switch method (goOnline(), goOffline()) must be in place All wait methods should be functioning properly and ...

Scraping website content in real-time using Vue or JavaScript

Is there a way to extract data from a website once it has been fully loaded? I have a process that iterates in a loop from 1 to 200, and I need to capture the results in the HTML once it reaches 200. 1. Can this be done? I am familiar with cheerio but un ...

focusing on every item within a container

Currently, my code looks like this: $(".container a").css("color","#ffffff"); It styles all links inside the ".container" element to be white. However, I have a div that has the following structure: <div class="container"> <div class="header" ...

Converting API-generated JSON data into an HTML table

My goal is to retrieve time and temperature data for all seven days from a JSON response obtained after querying an external weather API, specifically the Open Meteo service. I am struggling to populate an HTML table with this data. Below is the code snip ...

Images in Angular app not visible on Github Pages post deployment

Just starting out with Angular here. After successfully deploying a sample webpage to Github Pages, I noticed that the images which displayed fine on localhost are now returning a 404 error in the console. Below is the code snippet for the component conta ...

What is the best way to display a success message once a correct submission has been made in JavaScript?

I need to implement a success alert message in JavaScript using Bootstrap alerts after a form submission. When the code is executed, I can see the object array values in the console log. My goal is to display a success alert if the form submission is succe ...

Is there a way to extract the MIME type from a base64 string?

My base64 String appears as "UklGRkAdEQBXQVZFZm10IBIAAAABAAEAg...". I am attempting to download this file using my browser. Therefore, I convert it to a blob with the following function: b65toBlob: function(b64Data, sliceSize = 512) { ...

AngularJS: How to monitor variables without using $watch

I recently came to understand that Javascript operates on a "Call by sharing" principle, which means that everything is passed by value but the original contents of an object can still be modified. To illustrate this concept, consider the following scenari ...

Struggling to locate an item on myanimelist.net using the Selenium package in Python

https://i.sstatic.net/frvcC.png https://i.sstatic.net/trukj.png https://i.sstatic.net/UnY33.png I am encountering issues where I cannot retrieve any information despite using various methods such as classes, titles, and partial link texts to identify di ...