What is the best way to handle returning two promises and ensuring that the code waits for their execution to be completed?

Struggling with a code like the one below

I am attempting to make the function return true if the user is the current user. However, the issue I am facing is that the code execution does not wait and completes before this section of code is executed?

Would it be necessary to use async and await in this scenario?

What steps should I take in Typescript to ensure that the program waits to obtain the value of `resultSet` here?

P.S : I am still new to Typescript

        const resultSet=  WorkItemFormService.getService().then(
            function(ServiceWTest){               

                const b=ServiceWTest.getFieldValues([userField]).then(function(value)
                {
                    var a=false;
                    if(currentUser==actualUser)
                    {
                        a=true;

                    }
                    else
                    {

                    }
                    return Promise.resolve(a);
                });  
            return Promise.resolve(b);
        });

        var actiona=resultSet.toString();

Answer №1

It appears that the question lacks sufficient context and may require some cleanup before it can be fully understood. For example, the origin of actualUser is unclear, and the usage of the value variable within the inner function needs clarification.

Generally speaking, in the broader scope of things, utilizing async/await could provide a suitable solution. If I interpret your intention correctly, you might be seeking something along these lines:

async function myFunction() {
  const ServiceWTest = await WorkItemFormService.getService();
  const actualUser = await ServiceWTest.getFieldValues([userField]);
  const isCurrentUser = currentUser === actualUser;
  // It would be advisable to invoke a callback at this point to handle the outcome of determining "is this the current user?"
  doSomethingWith(isCurrentUser);
}

If using promises, the approach could resemble the following:

WorkItemFormService.getService().then(ServiceWTest => (
  ServiceWTest.getFieldValues([userField]).then(actualUser => (
    actualUser === currentUser
  )
)).then(isActualUser => {
  doSomethingWith(isActualUser)
}

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 InAppPurchase Plugin in Cordova is throwing the error message "Encountered an error: Cannot access the 'getProducts' property as it is undefined."

Currently, I am utilizing the cordova in-app-purchase plugin for my application. However, I am encountering an error that reads "ERROR TypeError: Cannot read property 'getProducts' of undefined" The .ts file appears as follows: window['plu ...

Are you on the lookout for an Angular2 visual form editor or a robust form engine that allows you to effortlessly create forms using a GUI, generator, or centralized configuration

In our development team, we are currently diving into several Angular2< projects. While my colleagues are comfortable coding large forms directly with Typescript and HTML in our Angular 2< projects, I am not completely satisfied with this method. We ...

When using MERN Stack (with Typescript) on DigitalOcean, encountering an issue where HTML files are displayed instead of JS and

Upon checking the console, I encountered this https://i.sstatic.net/PWoT5.jpg The app has been developed using Ubuntu and Nginx so far with no firewall configuration yet in place. This is my first time deploying a MERN stack and utilizing DigitalOcean. ...

Resolving the issue of 'type' property missing but required in 'SeriesXrangeOptions' within the Angular Highcharts module

I'm attempting to showcase a price chart view for a specific cryptocurrency chosen from a list of cryptocurrencies, but I keep encountering a type mismatch error. Within my application, I have utilized the angular-highcharts module and brought in the ...

Tips for preserving shopping cart in Angular?

As I delve into Angular, my goal is to create a straightforward ecommerce platform that allows users to add items to their cart, view them, and complete a checkout process. To accomplish this, I have set up three components: the products list, cart, and c ...

Display identical text using JavaScript filter

My search filter highlight is currently displaying [object Object] instead of <mark>match values</mark> when replacing the values. This is the code I am using: this.countries.response.filter((val) => { const position = val.value.toLowerCa ...

Is it possible to assign a variable in typescript using the interface as its type?

Here's the snippet of code I have written interface apiResult { Token: string; Result: any; } const result: apiResult = payload.Result; I am wondering about the significance of this code. Is it possible to assign a type from an interface to ...

Using Try...catch compared to .catch

Within my service.ts file, I have various user service functions that handle database operations. export const service = { async getAll(): Promise<User[]> { try { const result = await query return result } catch (e) { rep ...

What is the best way to access private properties within an extended Angular Component utilizing a directive?

I'm currently in the process of enhancing the functionality of the PoStepperComponent from the @po-ui/ng-components library within an Angular project. One specific requirement is to extend this component to introduce custom features. The plan entails ...

Dynamic Autocomplete Text Input featuring API-supplied Array in Angular

Currently, I am exploring the process of populating a text box with user emails obtained through an API call to the server. select-users.component.html: <input type="text" placeholder="Email Search" aria-label="Email" matInput [form ...

Encountered Angular SSR Serve Error: NullInjectorError - StaticInjectorError in AppServerModule with the following reference:

While working on building an application with Angular's SSR and serving it, I encountered a specific error. All services and components have been properly injected. Error: ERROR Error [NullInjectorError]: StaticInjectorError(AppServerModule)[REQUEST] ...

`AngularJS Voice Recognition Solutions`

In my quest to implement voice recognition in an AngularJS application I'm developing for Android and Electron, I've encountered some challenges. While I've already discovered a suitable solution for Android using ng-speech-recognition, fin ...

Do you think it is essential to run NPM install?

I am developing an NPM library that utilizes socket.io and is being written in Typescript. Imagine my library contains a function like this: public someFunction = (_socket: Socket) => {} When using my library in an application, only this function is ...

The use of conditional mapping with unions can render functions uninvokable

type Container<T> = T extends any[] ? ArrayContainer<T> : ObjectContainer<T> type ArrayContainer<T> = { set(arr: T, index: number): void } type ObjectContainer<T> = { set(obj: T): void } const testCont ...

Utilizing class-validator for conditional validation failure

Implementing conditional validation in the class-validator library using the given example, I need to ensure that validation fails if the woodScrews property is assigned a value when the tool property is set to Tool.TapeMeasure. I've searched extensiv ...

Ways to prevent a single element from being included in the selection of the entire

Here is my question: I am facing an issue with a context menu that should only disappear when clicking outside of a specific row within that menu. The element I want to exclude, with the id "except", is buried deep within multiple parent elements in my co ...

Issue encountered while deploying Next.js application on vercel using the replaceAll function

Encountering an error during deployment of a next.js app to Vercel, although local builds are functioning normally. The issue seems to be related to the [replaceAll][1] function The error message received is as follows: Error occurred prerendering page &q ...

The Angular NGRX action payload seems to undergo modifications between dispatching and execution

Angular v10, NGRX v10 I am facing a perplexing issue with my Plan object and Task properties using Angular v10 and NGRX v10. Despite making updates to Task properties within my TaskService by deep cloning the Plan object and dispatching an Action to updat ...

Creating Blobs with NSwag for multipart form data

The Swagger documentation shows that the endpoint accepts multipart form data and is able to receive form data from a client. However, the TypeScript client generated by NSwag appears to be unusable as it only accepts Blob. uploadDoc(content:Blob): Observ ...

Components in Angular do not refresh after using router.navigate

I currently have two main components in my Angular project: users.components.ts and register.components.ts. The users.components.ts displays a table of users, while the register.components.ts is where users can be added or edited. After making changes to ...