Promise in JavaScript | Async Calls | Dynamics CRM

I am going to explain how we can use promise in our CRM script with little explanation about promise.

Let's suppose you have multiple functions in your script and one of those function (name funA) does take time to execute and other function (name funB) in script depends on the result of that function (funA) result.

A 'promise' is a special JavaScript object that links both these functions; funA & funB together. Promise makes the result available to funB when it is ready from functionA.

Basic syntax of a promise is:

    var promise = new Promise(function (resolve, reject) {
            //Producing code
            let condition = 1;
            if (condition < 1)
                resolve();
            else
                reject();
        });

The function passed to new Promise is called the executor. When new Promise is created, it runs automatically. It contains the producing code, that should eventually produce a result. When the executor obtains the result, be it soon or late – doesn’t matter, it should call one of these callbacks:


  • resolve(value) — if the job finished successfully, with result value.
  • reject(error) — if an error occurred, error is the error object.
Below is the basic example of a constructor promise and how effectively we can use promise in our code.


      var winPlayOffs = function () {
            return new Promise(function (resolve, reject) {
                var isWon = true;
                if (isWon)
                    resolve('We won the playoffs');
                else
                    reject('We lost the Playoffs');
            });
        };
        var winSemiFinal = function (message) {
            return new Promise(function (resolve, reject) {
                var isWon = true;
                if (isWon)
                    resolve(message + ' | We won the Semi Final match');
                else
                    reject(message + ' | We lost the Semi Final match');
            });
        };
        var winFinal = function (message) {
            return new Promise(function (resolve, reject) {
                var isWon = false;
                if (isWon)
                    resolve(message + ' | We won the Final match');
                else
                    reject(message + ' | We lost the Final match');
            });
        };
        winPlayOffs().then(function (result) {
            return winSemiFinal(result);
        }).then(function (result) {
            return winFinal(result);
        }).then(function (result) {
            console.log('Result: ' + result);
        }).catch(function (result)
        { console.log('Result: ' + result); });


In practice, an executor usually does something asynchronously and calls resolve/reject after some time like the below sample code, but it can call resolve or reject immediately too.


    let promise = new Promise(function (resolve, reject) {
            // not taking our time to do the job
            resolve(123); // immediately give the result: 123
        });


Async Calls in CRM

In the below sample code, first of all I am checking the user info and and then reading the data from 'Incident' entity to get some values and return the same value after formatting in a required syntax.


  function onload(){
   getCurrentUserInfo()
.then(getCaseFromCMP);
}

function getCurrentUserInfo() {
            return new Promise(function (resolve, reject) {

                // call user info endpoint to see who this currently logged in user is
                var endpoint = "/api/data/v8.2/WhoAmI";
                var req = getXmlHttpRequestForCMP(endpoint);
                req.onreadystatechange = function () {
                    if (req.readyState === 4 && req.status == 200) {
                        var result = JSON.parse(this.response);
                        if (result) {
                            console.log("current user", result);
                            resolve(result["UserId"]);
                        }
                        resolve();
                    }
                };
                req.send();
            });
        }
        function getCaseFromCRM() {
            return new Promise(function (resolve, reject) {
                // setup API call to get the case from CRM
                var endpoint =
                    "/api/data/v8.2/incidents?$select=title,new_caseinfo,incidentid,_new_casecountryid_value,description&$filter=title eq '" +
                    caseNumber +
                    "'";
                var req = getXmlHttpRequestForCMP(endpoint);
                req.onreadystatechange = function () {
                    if (req.readyState === 4 && req.status == 200) {
                        req.onreadystatechange = null;
                        if (req.status === 200) {
                            var results = JSON.parse(this.response);
                            if (results) {
                                var result = results.value[0];
                                if (result) {
                                    incidentId = result["incidentid"];

                                    var _new_casecountryid_value = result["_new_casecountryid_value"];
                                    var _new_casecountryid_value_formatted = result["_new_casecountryid_value@OData.Community.Display.V1.FormattedValue"];
                                    var _new_casecountryid_value_lookuplogicalname = result["_new_casecountryid_value@Microsoft.Dynamics.CRM.lookuplogicalname"];

                                    var description = result["description"];
                                    var new_caseinfo = result["new_caseinfo"];
                                    var title = result["title"];
                                    // set variables:  &variables=NAME|VERSION&values=Aayush|54.0
                                    Variables += "&variables=title|description|new_caseinfo|countryCode";
                                    Variables += "&values=" +
    title +
    "|" +
    description +
    "|" +
    new_caseinfo +
    "|" +
    _new_casecountryid_value_formatted;
                                }
                            }
                            // resolve our promise
                            resolve();
                        } else {
                            alert("Case Record lookup error");
                            // resolve our promise
                            resolve();
                        }
                    } // end onreadystatechange
                };
                // send out http call
                req.send();
            }); // end of promise return
        }

function getXmlHttpRequestForCMP(endpoint, verb) {
            if (!verb) {
                verb = "GET";
            }
            var req = new XMLHttpRequest();
            req.open(verb, endpoint, true);
            req.setRequestHeader("OData-MaxVersion""4.0");
            req.setRequestHeader("OData-Version""4.0");
            req.setRequestHeader("Accept""application/json");
            req.setRequestHeader("Content-Type""application/json; charset=utf-8");
            req.setRequestHeader("Prefer"'odata.include-annotations="*"');
            return req;
        }

Comments

Popular posts from this blog

How to show enlarge image when mouse hover on image or link in Asp.Net(c#) using JavaScript

StateCode and StatusCode Values for mostly used entities in Microsoft Dynamics CRM 2013

Search data in Gridview on Textbox Key press event using JQuery in Asp.Net- C#

go to top image