Using arrow functions with CRM WebApi version 9 and typescript is not supported

I am currently in the process of upgrading the JavaScript code to the latest V9 version of Dynamics 365, and I am facing an issue where I cannot utilize arrow functions when working with Xrm.WebApi (also transitioning from JavaScript to TypeScript).

For instance, the following code snippet does not seem to work:

Xrm.WebApi.retrieveMultipleRecords(
                'mks_entitlementline',
                `$select=mks_name, _mks_parententitlementid_value&$filter=_mks_parententitlementid_value eq '${eId}'`).then(
                    (results) => {
                        if (!this.commonUtils.isUndefinedOrNull(results) && results.entities.length > 0) {
                            this.usesELS();
                        } else {
                            this.notUsingELS();
                        }
                        // filter contact lookup                        
                        this.filterContactLookup("", eId);
                        this.refreshPriorities(eId);
                        if (this.commonUtils.isUndefinedOrNull(this.formContext.getAttribute<Xrm.Attributes.LookupAttribute>('primarycontactid').getValue())) {
                            this.formContext.getControl<Xrm.Controls.LookupControl>('primarycontactid').setDisabled(false);
                        }
                    }).catch(error => {
                        console.log("ERROR -> entitlementSlaManagementOnUpdate: ", error);
                        Xrm.Utility.alertDialog("Error----", () => { });
                    });

However, the following piece of code seems to function (though appearing less elegant in my opinion):

Xrm.WebApi.retrieveRecord("role", searchedId, "$select=name")
                    .then(
                        function (role: { roleid: string, name: string }) {
                            outArr.push({ Id: role.roleid, Name: role.name, Type: "role" });

                            if (rolesAndTeams.length === outArr.length) {
                                if (!error) {
                                    _onOk(outArr);
                                }
                                _onErr(errorObject)
                            }
                        },
                        function (err) {
                            errorObject = err;
                            error = true;
                        })

The error message I'm encountering states:
Xrm.WebApi.retrieveMultipleRecords(...).then(...).catch is not a function

This essentially informs me that 'catch' is invalid, but I am unsure why it is flagged as such since the TypeScript compiler accepts it... I have also attempted configuring the tsconfig file to output on es5 and es2017 without success.

Therefore, the question remains - can arrow functions be utilized with Xrm.WebApi? If so, what am I doing wrong or failing to do?

Thank you in advance!

Answer №1

It seems that the issue may not be related to arrow functions, but rather with the use of catch. The compiler might not provide any feedback if the return value is of type any. To address this, take a look at the CRM API signature:

Xrm.WebApi.retrieveMultipleRecords(entityLogicalName, options, maxPageSize).then(successCallback, errorCallback);

Instead of using catch, you can pass the errorCallback directly to the then method.

In the second example, the errorHandler is passed in a similar manner.

To resolve this, consider implementing the following approach:

Xrm.WebApi.retrieveMultipleRecords(
            'mks_entitlementline',
            `$select=mks_name, _mks_parententitlementid_value&$filter=_mks_parententitlementid_value eq '${eId}'`).then(
                (results) => {
                    if (!this.commonUtils.isUndefinedOrNull(results) && results.entities.length > 0) {
                        this.usesELS();
                    } else {
                        this.notUsingELS();
                    }
                    // filter contact lookup                        
                    this.filterContactLookup("", eId);
                    this.refreshPriorities(eId);
                    if (this.commonUtils.isUndefinedOrNull(this.formContext.getAttribute<Xrm.Attributes.LookupAttribute>('primarycontactid').getValue())) {
                        this.formContext.getControl<Xrm.Controls.LookupControl>('primarycontactid').setDisabled(false);
                    }
                },
                error => {
                    console.log("ERROR -> entitlementSlaManagementOnUpdate: ", error);
                    Xrm.Utility.alertDialog("E----", () => { });
                });

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 'MY_EVENTS_LOAD' argument is incompatible with the 'TakeableChannel<unknown>' parameter in the yeild takeLatest function

I am encountering a TypeScript error while using Redux and Saga as middleware. The error message is as follows: No overload matches this call. The last overload gave the following error. Argument of type '"MY_EVENTS_LOAD"' is not assignabl ...

How can we leverage the nullish coalescing operator (`??`) when destructuring object properties?

When working with ReactJS, I often find myself using a common pattern of destructuring props: export default function Example({ ExampleProps }) { const { content, title, date, featuredImage, author, tags, } = ExampleProps || {}; ...

Set the array as the object attribute

Transitioning my app from AngularJs to Angular 4 has been quite a challenge. I've noticed that the type of statements I frequently used in my code are now failing in Angular 4 (TypeScript): Update: The following lines were previously used in Angular ...

Angular displays X items in each row and column

I've been struggling with this task for the past 2 hours. My goal is to display a set of buttons on the screen, but I'm facing some challenges. The current layout of the buttons doesn't look quite right as they appear cluttered and unevenly ...

Generate a new data type based on the value of a single attribute within a collection of objects

Is there a way to extract a specific property of a combined type and generate a new type from it? Consider the following example: type Actions = | { type: "ADD_COLUMN"; newColumnIndex: number; column: SelectorColumnData; } | { type: ...

The process of creating Jasmine tests for an Angular 2 Observable

Currently, I am in the process of testing a component that involves calling a service. My goal is to effectively stub or mock the service in order to control its return value and manipulate the component variables within the callback/success function of ...

Utilize TypeScript to narrow down function parameters within a callback by evaluating other parameters

I'm currently working with traditional node callbacks. For example: myFunction('foo', (err: Error|null, data?: Buffer) =>{ if (err) { // typeof err is Error // typeof data is Buffer|undefined } else { // typeof err is nul ...

Steps for calculating the average of several columns within a table using Angular 10

Currently, I have a function that successfully calculates the sum of JSON data in all columns on my tables. However, my attempt to get the average of each column is resulting in NaN or infinity. What could be the issue here? Here is my current implementat ...

What is the appropriate interface for determining NavLink isActive status?

In the process of crafting a "dumb" component using NavLink, I am defining the props interface for this component. However, I encountered an issue when trying to include isActive in the interface. It's throwing errors. I need guidance on how to prope ...

Is it beneficial to utilize an interface for constructing a class model?

The Interface: export interface IAddEditGeneralDictionary { Code: string; StartDate?: Date | string; FinishDate?: Date | string; Name: string; } The Realization: export class AddEditGeneralDictionary implements IAddEditGe ...

Ever tried asynchronous iteration with promises?

I have a specific code snippet that I am working on, which involves registering multiple socketio namespaces. Certain aspects of the functionality rely on database calls using sequelize, hence requiring the use of promises. In this scenario, I intend for t ...

Steps to successfully pass a reference from a parent component to a child component that utilizes TouchableOpacity in React Native

I am facing an issue with passing a transitioning ref from a parent Transitioning view to a child component: const transition = ( <Transition.Together> <Transition.In type="fade" durationMs={300} /> <Transition.Change /&g ...

What to do when calling disabled() on a FormControlName causes all form fields to become invalid?

While working with a reactive form, I have observed that setting a formControlName to disabled() can cause the entire form to become invalid. Is there a way to ensure the form remains valid even after disabling a control? console.log('Before:' ...

What is causing the undefined value for the http used in this function?

My Code Component import { Component, OnInit } from '@angular/core'; import { Http } from '@angular/http'; @Component({ selector: 'app-root', template: '<button id="testBtn"></button>' }) export c ...

Preventing style conflicts in react-native with styled-components

Attempting to customize the properties of a button in the calling component using styled-components, but encountering issues. The overriding of properties does not seem to be successful, and the button appears unchanged. The button is defined as follows: ...

"Encountering connectivity issues between NestJs and TypeORM when trying to establish a

My current challenge involves connecting to MySQL. I have set the database connection variables in a .env file located in the root directory, and I am initializing the connection in the app.module.ts file. The problem arises when I attempt to create or run ...

Compiling a solo Typescript file is taking an unexpectedly long time

I recently started learning Typescript and encountered a slow compilation issue while following a tutorial on Youtube. When I run tsc myfile.ts, it takes about 40 seconds to compile, even though my file is short with just basic Javascript code for understa ...

React throwing a typescript error while attempting to update state based on the previous state

Hello there! I'm fairly new to working with TypeScript and I've encountered an issue with a piece of state in a child component. I'm trying to modify it based on the previous value, but every time I call the setState function, I get a type e ...

Is it possible to compile using Angular sources while in Ivy's partial compilation mode?

Error: NG3001 Unsupported private class ObjectsComponent. The class is visible to consumers via MasterLibraryLibModule -> ObjectsComponent, but is not exported from the top-level library entrypoint. 11 export class ObjectsComponent implements OnInit { ...

Standard layout for a project with equally important server and client components

We are in the process of developing an open-source library that will consist of a server-side component written in C# for Web API, meta-data extraction, DB operations, etc., and a client-side component written in TypeScript for UI development. Typically, ...