Passing values dynamically between classes in Typescript is a convenient way to share

UPDATED:

I've encountered an issue with my cucumber test scenario:

Given I set some value
Then I print it

Here is the related code from two different classes:

export class XXX {

  searchedValue: string;

  @given("I set some value")     
  public async getInfoData(){
    this.searchedValue = await getData.getPlayersId();
  }
}

And another class:

export class YYY {
  const xxx = new XXX();
            
  @then("I print it")
  public async showData(){
    console.log( await xxx.searchedValue)
  }
}

When running the I print it step, it returns undefined instead of passing the expected value. Any assistance would be greatly appreciated.

Answer №1

One possible approach could be:

class AAA {
  searchData: Promise<string> = Promise.resolve('');
    
  async fetchInfo() {
    this.searchData = fetchData.fetchDocument();
  }
}

Next, you can have:

class BBB {
  const aaa = new AAA();
        
  async displayInfo() {
    console.log(await aaa.searchData)
  }
}

Lastly:

const b = new BBB();
await b.displayInfo(); // will show an empty string
b.aaa.fetchInfo(); // whoever and whenever triggers that
await b.displayInfo(); // will display the result of fetchDocument() when available

Keep in mind that fetchInfo() must be called before displayInfo() if you want to wait for the outcome. It is important to understand the timing and handling of Promises.

In general, your design may need refinement.

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

How can I adjust the column width in OfficeGen?

Currently, I am utilizing officeGen for the purpose of generating word documents. <sup> let table = [ [ { val: "TT", fontFamily: "Times New Roman", }, { val: "Ten hang", ...

Managing state within SolidJS components using Immer's "produce" for nested state handling

I've been working on a SolidJS application where I store a large JSON object with nested objects. For undo and redo actions, I'm using Immer to generate patches. Although technically I'm storing a class with multiple layers of nesting, Immer ...

What steps should I take to correctly identify the type in this specific situation?

Let's consider the function f, defined as follows: function f<T extends Fields = Fields>(props: Props<T>) { return null; } In this context, T represents a generic type that extends Fields. The concept of Fields is captured by the follow ...

Struggling with continuously re-rendering a color background when using useMemo in React?

After every re-render, a new color is generated. Is there a way to store the initial color and reuse it in subsequent renders? const initialColor = generateNewColor(); // some random color const backgroundColor = React.useMemo(() => { return ...

The selected image should change its border color, while clicking on another image within the same div should deselect the previous image

https://i.sstatic.net/jp2VF.png I could really use some assistance! I've been working on Angular8 and I came across an image that shows how all the div elements are being selected when clicking on an image. Instead of just removing the border effect f ...

Encountered a runtime error in NgRx 7.4.0: "Uncaught TypeError: ctor is not a

I'm facing difficulties trying to figure out why I can't register my effects with NgRx version 7.4.0. Despite simplifying my effects class in search of a solution, I keep encountering the following error: main.79a79285b0ad5f8b4e8a.js:33529 Uncau ...

The error "ReferenceError: window is not defined" occurs when calling client.join() due to

I am looking to create a video call application using React and Next.js with the AgoraRTC SDK. After successfully running AgoraRTC.createClient(), AgoraRTC.createStream(), and client.init(), I encountered an error when trying to execute client.join(). The ...

Accessing JSON object from a URL via a web API using Angular 2 and TypeScript

`Hello, I am in need of some assistance in retrieving JSON data from a web API using Visual Studio 2015 .net Core, Angular 2 & Typescript. The Angular2 folders are located in /wwwroot/libs. Currently, I am utilizing Angular 2's http.get() method. Ho ...

Tips for clearing out text in a <p> tag with javascript when it exceeds a specific length of 100 characters

Is there a way to automatically truncate text to (...) when it exceeds 100 characters inside a paragraph with the class .class? For instance, if I have a long paragraph like this: <div class='classname'> <p>Lorem ipsum dolor sit ame ...

Eslint encountered an issue while parsing: Unable to access tsconfig.json

My directory structure looks like this: -projects --MyProject ---MyDir tsconfig.json eslinttrc.json Inside my eslinttrc.json file, I have the following configuration: "parserOptions": { "ecmaVersion": " ...

Enhance your TypeScript classes with decorators that can add new methods to your class

Can you explain property definition using TypeScript and decorators? Let's take a look at this class decorator: function Entity<TFunction extends Function>(target: TFunction): TFunction { Object.defineProperty(target.prototype, 'test& ...

Iterating over a specified number of times using the for..of loop in Typescript

In my quest to find a way to loop through an array a specific number of times using the for..of function in TypeScript, I have come across numerous explanations for JavaScript, but none that directly address my question. Here is an example: const someArra ...

Instructions on enabling Angular 2 to detect dynamically added routerLink directive

As illustrated in this Plunker, I am dynamically injecting HTML into one of my elements, which can be simplified as follows: @Component({ selector: 'my-comp', template: `<span [innerHTML]="link"></span>`, }) export class MyCo ...

Dealing with Alias complications in Typescript/ts-node/tsc

I've got this script in the root directory of my project: // ./root-dir.ts import * as url from "url"; export const rootDir = url.fileURLToPath(new URL(".", import.meta.url)); My tsconfig.json configuration looks like this: { ...

Creating a shared module for Ionic 3 to handle pipes specifically for lazy loaded pages

Lazy loading in Ionic 3 is achieved using IonicPage and IonicPageModule, but unfortunately, lazy loaded pages do not have access to pipes. Failed to navigate: Template parse errors: The pipe 'myPipe' could not be found ("") This question a ...

Exploring TypeScript: Navigating the static methods within a generic class

I am trying to work with an abstract class in TypeScript, which includes an enum and a method: export enum SingularPluralForm { SINGULAR, PLURAL }; export abstract class Dog { // ... } Now, I have created a subclass that extends the abstract cla ...

navigating up to the parent element and then back down to the child element using

<div class="classA"> <label class="classB"> <span>Referral Date</span> </label> <div> <input class="classC"> </div> </div> I am coding with ...

TypeScript function encountering issues with proper evaluation of set iteration

Whenever I attempt to run the code below, I consistently receive this console message: "undefined is not an object (evaluating 'this.courseAvailThisTerm')". Even though the courseAvailThisTerm() function functions properly in other scenarios. Any ...

What is the best way to parse JSON data with Typescript?

I am dealing with JSON data structured as follows: jsonList= [ {name:'chennai', code:'maa'} {name:'delhi', code:'del'} .... .... .... {name:'salem', code:'che'} {name:'bengaluru' ...

The module './$types' or its related type declarations could not be located in server.ts

Issue with locating RequestHandler in +server.ts file despite various troubleshooting attempts (recreating file, restarting servers, running svelte-check) +server.ts development code: import type { RequestHandler } from './$types' /** @type {imp ...