How can I create a versatile function in Javascript that pauses execution until one of a series of events takes place?

Transitioning to Protractor as a UI automation framework after extensive use of Selenium in Java, Ruby, and Groovy has presented me with new challenges. As a newcomer to Javascript, I'm uncertain about the transferability of my previous techniques.

In Ruby and Groovy, I found a "multiwait" library particularly helpful for waiting on a set of mutually exclusive events. This library involved a map where keys described events and values were executable code chunks. The function would iterate through each event, returning the key when an event returned true. If no event returned true within a specified timeout, an Exception summarizing the events and wait time was thrown. Additionally, there was a special "nothing" event for scenarios where an action might not trigger any response if data was good. In such cases, the function would return the key for the "nothing" event instead of throwing an Exception.

Now, I am attempting to replicate this functionality in Javascript, facing the challenge of adapting to the language's syntax and features.

I understand that functions can be stored as variables in Javascript. Should I consider using functions as event values in a Hash Table for this purpose? Will it introduce scope issues, or should everything work smoothly as long as each function can access the necessary variables?

If someone could provide me with a simple example, it would greatly assist me. Let's assume I have a page object with a method getColor which always returns the String red. I aim to create a method in another file that accepts a Hash Table of events like:

var WaitForEvent = require('../../waitForEvent');
var wait = new WaitForEvent();

function getColor() {
  return 'red';
}

var outcomes = {};
outcomes['Data accepted'] = function () { getColor() == 'green' };
outcomes['Data rejected'] = function () { getColor() == 'red' };

var result = wait.waitFor(outcomes);

expect(result).toBe('Data accepted');

This outlines how I plan to define parameters for the method. Would functions like these be suitable for this scenario? Could a waitForEvent function effectively iterate through these functions, determining which one returns true first, and then return the corresponding event key? Or do I need to approach this differently?

If this approach is viable, how should the method handle looping through nameless functions within the Hash Table values? What is the correct way to execute and evaluate the return value of such functions?

While familiar with Selenium's ExpectedConditions feature, chaining conditions with the OR operator, I seek a more flexible alternative.

Thank you!

Answer №1

Suppose you have the following code (translated to ES6):

const getColor = () => 'red';
outcomes['Data rejected'] = () => getColor() === 'red';

With this, you can now run:

let keys = Object.keys(outcomes).filter(k => outcomes[k]())

and keys[0] will return 'Data rejected' instead of undefined. However, if you want to "wait" for it, you would need to wrap it in an async function with some setTimeouts.

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

AngularJS provides a way to create opening pages with clickable buttons for a

I'm struggling to implement buttons that switch ons-templates when clicked. I've been following this example as a reference: Here's the code snippet I've been working on, but it just won't cooperate: <!doctype html> &l ...

Struggling to find the correct CSS path for the login input field

I am currently attempting to scrape a website that requires login credentials. However, I am encountering difficulty in obtaining the correct CSS-Path (or XPath) for the login form. The login page can be found here: When using Chrome: SelectorGadget on ...

Performing AJAX requests to dynamically update multiple DIVs

Encountering difficulties with adding additional input fields to a page, each of which contains jquery code for appending more select boxes related to them. The base html setup is as follows: <p id="add_field"> … </p> <div class="show_sub ...

Error occurring when attempting to pass messages within an iframe on a sandboxed page in a Chrome extension

Whenever I try to utilize my popup page for a chromium extension as a conduit for communication between the background page and a page shown within an iframe on the popup, I encounter the following error. I required a sandboxed environment to execute Vue.j ...

The Typescript Decorator is triggered two times

I submitted a bug report regarding Typescript because I suspect there is an issue, although I'm seeking additional insights here as well. This is the scenario. When running the following code: class Person { @IsValueIn(['PETER', ' ...

Step-by-step guide on generating and showcasing an event exclusively using the Calendar Strip React Native npm module

I recently started exploring the world of React Native and Expo, and I have been diving into the documentation for Calendars in React Native and Expo. During my research, I came across a fantastic npm package called Calendar Strip that caught my attention. ...

What is causing the process to terminate without triggering an error when using `stream.read()` or `stream.once('readable')`?

My exploration of readable.read() and readable.once('redable') took an unexpected turn when I encountered a strange issue. It appears that either one of the above methods is causing my node.js process to abruptly terminate without any error messa ...

What are the top Navigation options in SharePoint 2010?

I have customized the default top navigation in SharePoint 2010 using CSS styles. However, I also want to enhance it by adding icons (.png images) for each navigation menu item. For example, I would like to add an icon next to "Home", another one next to " ...

Nuxtjs is functioning properly on 127.0.0.1:5000, but unfortunately it is not working on localhost:5000

Currently, I'm working on a project with Nuxtjs. The application opens successfully when I use the URL 127.0.0.1. However, when I attempt to access it through localhost:5000, I receive the error message Access to localhost was denied. You don't h ...

Unexpected error encountered in Angular 2 beta: IE 10 displays 'Potentially unhandled rejection [3] SyntaxError: Expected'

Question regarding Angular 2 Beta: I am starting off with a general overview in the hopes that this issue is already recognized, and I simply overlooked something during my research. Initially, when Angular 2 Beta.0 was released, I managed to run a basic m ...

Looking for a way to locate the point where objects intersect in three.js?

My goal is to load 20 objects with random positions in a way that they do not intersect. How can I detect and check for intersections between these objects? for (var i = 0; i < 20; i++) { // Create a material var textureLoader = new ...

What is the method for prompting a save as dialog in the browser in order to save JSON data stored in memory?

As the title suggests, I am looking for a way to store JSON data in memory. I want this action to be triggered by an onclick event on a DOM object. The goal is to save the data on the user's computer as if they were downloading a file. Saving it as t ...

In Photoshop scripting, trying to manipulate an undefined object is like trying to find

I am facing an issue in Photoshop while trying to create a grommet using a script. The error message I receive is: Error: undefined is not an object line 63 ( grommetMarkL = printMarksLayer.pathItems.ellipse( -(spacingY), spacingX, grommetSize, gromm ...

[server-auth]: The `useSession` function is required to be enclosed within a <SessionProvider /> component to avoid the error occurring in the current JavaScript file

While trying to validate authentication by following the next-auth documentation, I encountered an error stating "[next-auth]: useSession must be wrapped in a SessionProvider". I am using GitHub credentials for the validations. Here is my code: Currently ...

Edit esri pop-up template

Can I customize the popupTemplate in Esri to match my design? I currently have a popupTemplate set up like this: popupTemplate: { content: [{ type: "fields", fieldInfos: [{ fieldName: "Name" ...

Utilize javascript/jquery for transforming HTML table data to JSON

Whenever I click the "+" button, my table rows are dynamically generated. After populating the fields and clicking the submit button next to "+", the JSON data is displayed in the console, as shown in the image below. While generating the JSON data, I aim ...

Encountering the error message "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client" while attempting to identify duplicate entries in my database

I am currently working on a backend written in express.js that handles standard CRUD operations. My ORM of choice is sequelize. Here's the code snippet: import { Sequelize} from 'sequelize'; import User from '../Models/User.js'; im ...

Integrate JavaScript into your HTML code

I'm a beginner in HTML and am working on creating a login form. Here is the code that I have written so far. I need help with importing my JavaScript code into the HTML form. C:\Program Files\xampp\htdocs\forsiteSystem\thems& ...

Creating a Vue.js data object with items arranged in descending order

While working with vue.js, I encountered an issue in sorting the items stored in my data object. Currently, they are sorted in ascending order and I need to display them in descending order instead. Below is a snippet of my vue template: <div class="fo ...

Choose an option from the dropdown menu using Selenium

Issue I am encountering difficulty selecting a country from a drop-down menu in WooCommerce. <select name="shipping_country" id="shipping_country" class="country_to_state country_select select2-hidden-accessible" autocomplete="country" tabindex="-1" a ...