The closure appears to be ineffective

Here is my current code snippet:

private isLogged(): boolean {
    //check cookie here
    let logged: boolean;
    browser.manage().getCookies().then((cookies: IWebDriverOptionsCookie[]) => {
       if (cookies.length == 0) {
        console.log('Is Not Logged');
        console.log('My cookies', cookies);
        logged = false;
    });
    console.log('isLogged: ' , logged);
    return logged;
}

Upon executing this code, the value of "logged" variable is:

   undefined

I can see the messages "Is Not Logged" and "My cookies" being displayed.

Could it be that there is a simple mistake that I am overlooking due to tiredness?

Answer №1

Upon calling the isLogged() function and exiting it, keep in mind that the promise returned by the browser.manage().getCookies() method has not been resolved yet. This explains why the variable logged remains unset.

To address this issue, modify the isLogged function to return a promise as shown below:

private isLogged(): boolean {
    return browser.manage().getCookies().then(function (cookies) {
      if (cookies.length == 0) {
        console.log('Is Not Logged');
        return false
      } else {
        console.log('Is Logged');
        console.log('My cookies', cookies);
        return true
      }
    });
}

Then, resolve the promise when the value is required like so:

isLogged().then(function (isLogged) {
    console.log(isLogged);
});

To dive deeper into promises within Protractor, refer to the documentation page on Promises and the Control Flow.

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 returned by a component should remain consistent regardless of where it is invoked. Additionally, the main component in React should not re-render when the state of a sub-component is

I am looking to have the same value displayed in the Home function from the Component, without causing a rerender when the useState in Component is updated. import { useState, useEffect } from "react"; function Component() { const [count, setC ...

Extracting Information from a CSV File During a Drop Action

While attempting to upload and read CSV data, I am encountering issues with retrieving the data. The data is being dropped into the 'div' tag instead of the 'input' tag. onDrop = (e: React.DragEvent)=>{ console.log("the va ...

Can you delete angular attributes from HTML elements?

I delved into understanding the inner workings of Angular.js using a basic example. <div ng-app=""> <p>Type something in the input field:</p> <p>Name : <input type="text" ng-model="name" placeholder="Enter name here">< ...

What is the best way to access a variable within an event handler function?

Is there a way to retrieve values from the for-loop within an event handler? Consider this JSON array var items = [ { "id": "#id1", "name": "text1" }, { "id": "#id2", "name": "text2" } ]; that is passed as a parameter to the function function setHand ...

Obtain a numerical output from a selection of numbers

I am facing a simple problem that I can't solve due to my lack of knowledge and have not been able to find any solution online. What I want to achieve is: Create a "value 1" from an array of integers. Generate a random "value 2". Check if the rando ...

Issue arose when attempting to remove an item from an array within React

I have a handleAd function that adds new components to an array, and I also have a handleDelete function that is supposed to remove the selected element from the array. I am generating unique keys for each element to prevent deletion issues. Initially, th ...

What is the most graceful method to calculate the average date from an array containing moment.js dates?

I have been using the reduce method along with the dayOfYear function to calculate the average date from an array of dates. While my current solution functions well for dates within the same year, it unfortunately overlooks the discrepancy in years betwee ...

What are some ways to avoid an image looking faded when adding it to the scene background in Three.js?

I've been experimenting with loading images onto the scene background using the TextureLoader() class to prevent them from appearing greyed out. Following a tutorial on three.js https://www.youtube.com/watch?v=xJAfLdUgdc4&list=PLjcjAqAnHd1EIxV4FS ...

Browser-agnostic script proxy

Currently, I am working on client-side Javascript which interacts with JSON web services from a different domain. I've learned that certain browsers don't permit cross-domain scripting, so it's recommended to set up a proxy on my local serve ...

Exploring the Basics of MVC Routing in Express/Node.js

I am encountering an issue with routing in my application. I have set up a main index.js router, a secondary router file, and a controller, but for some reason, it is not routing correctly and results in a 404 error. Here is the content of routers/index.j ...

The comparison between 'MutableRefObject<string | null>' and 'string' will never be true, as they do not share any common types. Error code: TS2367

Struggling with a React and TypeScript issue I have stored the email and password in state variables const emailRef = useRef<string | null>(null); const passwordRef = useRef<string | null>(null); This is how I set them: const onEmailChange = ...

Store the result of an EJS include tag in a JavaScript variable

I have my footer HTML contained in the file named footer.ejs. I am looking to add this HTML dynamically to another page using JavaScript. The following code snippet does not seem to be functioning properly. Is there a way to store a template output in a J ...

"Caution: The `className` property did not align" when configuring a theme provider within Next.js

I'm currently working on developing a theme provider using the Context API to manage the application's theme, which is applied as a className on the body element. The implementation of the context is quite straightforward. When initializing the ...

What could be causing me to not receive the prepackaged error messages from Angular in my WebStorm 8?

Having some trouble here... my angular errors are always so cryptic, like this: I usually manage to figure out the issue on my own, but I'm really hoping someone can offer guidance on how to get those nice error messages that angular supposedly displ ...

Prisma and Next.js: Changes to content require re-deployment for updates to take effect

Just recently, I launched a new website on Vercel. My web application is being built with Prisma and Next.js. However, I'm currently facing an issue where the content doesn't update in real-time unless I manually re-deploy the application. Here&a ...

Currently struggling to retrieve data from an AJAX post request within a C# controller

I need assistance with sending data from JavaScript to a C# controller using AJAX. However, I am facing an issue where all the arguments in the Add method of my controller are showing up as null. Below is my AJAX code: function sendRequest(name, price, ab ...

Attempting to incorporate a variable into the URL while making an Ajax POST request using jQuery

Currently, I am attempting to create a post using jQuery.ajax instead of an html form. Below is the code I am using: $.ajax({ type: 'POST', // GET is also an option if preferred url: '/groups/dissolve/$org_ID', data: data, success: fu ...

What could be causing the function to not work properly within the React component?

Having trouble with a React component utilizing speech recognition for converting speech to text. Initialized the recognition functions within the component but encountering errors. Need assistance in troubleshooting this issue. const speechRecognition = w ...

Validation data not being transmitted in AJAX request

My PHP code is almost working perfectly, but I'm facing an issue with receiving the output of the validate function through AJAX. Can someone help me troubleshoot this problem? $(document).ready(function(){ $("#d").click(function(){ valid ...

Sharing information between different components in React can be done using props, context, or a

When attempting to edit by clicking, the parent information is taken instead of creating a new VI. I was able to achieve this with angular dialog but I am unsure how to do it with components. This is done using dialog: <div class="dropdown-menu-item" ...