Executing asynchronous functions within synchronous functions in TypeScript and returning a boolean value

Is there a way to call an asynchronous function from a synchronous function without encountering issues?

function showOpenCaseDialog(): boolean {

    let result = false;

    var regardingobjectid = (<Xrm.LookupAttribute<string>>Xrm.Page.getAttribute("regardingobjectid")).getValue();
    if (regardingobjectid != null && regardingobjectid.length > 0) {
        var regardingobject = regardingobjectid[0];
        if (regardingobject.entityType === "incident") {
            checkCaseLastOpenActivity(regardingobject).then(x => result = x);
        }
    }

    return result;
};

The function checkCaseLastOpenActivity is asynchronous in nature.

One issue encountered is that the synchronous function returns a value before the asynchronous operation is completed.

Are there any potential solutions to this problem?

Answer №1

Even though the code appears to be synchronous, it is actually functioning asynchronously.

Consider making the showOpenCaseDialog function an async function that returns a Promise<boolean>.

async function showOpenCaseDialog(): Promise<boolean> {

    let result = false;

    var regardingobjectid = (<Xrm.LookupAttribute<string>>Xrm.Page.getAttribute("regardingobjectid")).getValue();
    if (regardingobjectid != null && regardingobjectid.length > 0) {
        var regardingobject = regardingobjectid[0];
        if (regardingobject.entityType === "incident") {
            result = await checkCaseLastOpenActivity(regardingobject);
        }
    }

    return result;
};

Answer №2

If you want to leverage ES6 promises, give it a shot.

Wrap the async section in a promise and handle the return in the then block. See the example below:

var promise1 = new Promise(function(resolve, reject) { resolve(Xrm.Page.getAttribute("regardingobjectid").getValue()); });

promise1.then(function(regardingobjectid) {
    if (regardingobjectid != null && regardingobjectid.length > 0) {
        var regardingobject = regardingobjectid[0];
        if (regardingobject.entityType === "incident") {
            checkCaseLastOpenActivity(regardingobject).then(x => result = x);
        }
    }
});

Alternatively, you can directly return the promise from the function as needed.

For more in-depth information, check out https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Answer №3

executeAsyncOperation(param1, cb: (result)=> void) : any {
.....
this._backendRequest.makeRequest(param1)
 .subscribe(response=>{
 .......
 .......
 return cb(response);
  });
}

Example of using callback:

this.executeAsyncOperation(data1, (result)=>{
........
........
});

Example of using without callback:

this.executeAsyncOperation(data1, null);

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

Creating a function that can map various types of objects to a single type

type ShapeA = { id: number; length: string; width: string; height: string; } type ShapeB = { id: number; side1: string; side2: string; side3: string; } type Shapes = (ShapeA | ShapeB)[] type MappedShape = { id: number; dimension1: st ...

Using props in React can be declared either as a `type` or an `interface`

I am working with React code export default class MyComponent extends Component<Props,State> I'm trying to figure out whether I should define my props using a type or an interface. type Props = { isActive: Boolean, onClick: Function } ...

Turn off the touch events system for Ionic 2 on the leaflet map's draw controller

Seeking guidance on how to disable data-tap functionality in Ionic 2 within a leaflet map div. Anyone familiar with this? In Ionic-v1, the solution involved adding data-tap-disabled="true" to the map container (ion-content). I recently integrated the lea ...

Is it possible to use @ViewChild to target an element based on its class name?

The author of this article on Creating Advanced Components demonstrates selecting an element by creating a directive first: @Directive({ selector: '.tooltip-container' }) export class TooltipContainerDirective {} Then, the author uses this d ...

Using Typescript to collapse the Bootstrap navbar through programming

I've managed to make Bootstrap's navbar collapse successfully using the data-toggle and data-target attributes on each li element. If you're interested, here is a SO answer that explains a way to achieve this without modifying every single ...

Filtering a List Using Angular

I am working on a code where I need to filter a list of elements based on the option selected from a combobox. Currently, my code is error-free but I am unable to successfully filter the list. Can someone please guide me on what steps I should take next? ...

Managing Observable<Person[]> in ng-bootstrap typeahead instead of Observable<string[]>: a complete guide

I'm new to Angular/Typescript and have a question. I recently tried out the example from Wikipedia in ng-bootstrap typeahead. Instead of using the Wikipedia call, I decided to use a custom REST service that has the following GET endpoint: GET /pers ...

Ways to conceal a component based on a specific condition?

In my Angular 8 application, I need to dynamically hide a component based on a specific condition. The condition I want to check is: "status === EcheqSubmissionStatus.EXPIRED" Initially, I attempted the following approach: EcheqProcessComponent templat ...

Issue encountered in NestJS/TypeORM: Unable to modify the property metadata of #<Repository> as it only has a getter method

When attempting to launch my nestjstutorial app, I encountered the following error message. The backend is connected to a PostgreSQL database. TypeError: Cannot set property metadata of # which has only a getter at EntityManager.getCustomRepository (D:&b ...

Assign custom keys to request object parameters before reaching the controller in the map

I have a Loopback 4 application where the request object's property keys are in snake_case and they correspond to our database column names which are in StudlyCase. What I want is to change the application property names to camelCase. This means that ...

The data type 'null' is not a valid index type to be used in the Array.reduce() accumulator

This is a follow-up inquiry from: How can JavaScript convert multiple key-value pairs in object lists into one nested object? The initial objective was to merge numerous objects with various key-value pairs into a single nested object. For example, start ...

In the latest version of Expo SDK 37, the update to [email protected] has caused a malfunction in the onShouldStartLoadWithRequest feature when handling unknown deeplinks

After updating to Expo SDK 37, my original code that was previously functioning started encountering issues with <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e7c6b6f6d7a23606f7a67786b23796b6c78667f79627a">[email prot ...

What are the steps to achieve full screen mode in Google Chrome within an Angular 4 Application?

I'm working on an application and I'm looking to incorporate a feature where, when a user navigates from one component to another, the new component's ngOnInit method triggers the Chrome browser to enter full screen mode, similar to pressing ...

I'm having trouble grasping the concept of 'globals' in TypeScript/NodeJS and distinguishing their differences. Can someone explain it to me?

As I review this code snippet: import { MongoMemoryServer } from "mongodb-memory-server"; import mongoose from "mongoose"; import request from "supertest"; import { app } from "../app"; declare global { function s ...

Creating a dynamic CSS height for a div in Angular CLI V12 with variables

Exploring Angular development is a new venture for me, and I could use some guidance on how to achieve a variable CSS height in Angular CLI V12. Let me simplify my query by presenting it as follows: I have three boxes displayed below. Visual representatio ...

What is the best way to clear a form in a Next.js 13.4 component following a server action?

Currently, I am working on a component using next.js 13.4, typescript, and resend functionality. My code is functioning properly without clearing data from inputs, as it uses the "action" attribute which is commented out. However, I started incorporating ...

Jest is having difficulty locating a module while working with Next.js, resulting in

I am encountering some difficulties trying to make jest work in my nextjs application. Whenever I use the script "jest", the execution fails and I get the following result: FAIL __tests__/index.test.tsx ● Test suite failed to run ...

What is the best method to display a service property within a controller?

If we consider the scenario where I have a controller named ctrlA with a dependency called serviceB, which in turn has a property known as propertyC. My development environment involves Angular and Typescript. When interacting with the user interface, the ...

Closing a bootbox alert by clicking on a href link

Utilizing bootbox alert within my Angular2 application to present information to users on the UI. The alert message includes href links, and I want the page to navigate to the clicked link while also closing the bootbox modal. However, I am facing an issue ...

What is the best way to retrieve the current height in VueJS using the Composition API?

I am utilizing a Ref to preserve the current height of the active element. My goal now is to transfer this height to the subsequent element that gets clicked on. <script lang="ts" setup> import { ref, reactive } from "vue"; defin ...