Xrm WEBAPI Calls as Syncronous sample code using Promise
By default XRm WebAPI are asynchronous and to make this synchronous you can use below code structrure with using Promise.
ValidateZipCode: function (executionContext) {
"use strict";
var formContext = executionContext.getFormContext();
var postalcode = formContext.getAttribute(Resident.Fields.address1_postalcode).getValue();
var message = "Please enter a valid zip code";
var uniqueId = "cnt_postalcodenotpresent";
return new Promise(function (resolve, reject) {
Xrm.WebApi.retrieveMultipleRecords("new_postalcodes", "?$select=new_postalcode&$filter=hsg_postalcode eq '" + postalcode + "' ").then(
function success(result) {
var isNotFound = false;
if(result !== undefined)
isNotFound = result.entities.length === 0 ? true : false;
if (isNotFound) {
var errorMessage = "Postal Code Mapping is not present for the given postal code"
formContext.ui.setFormNotification(errorMessage, "ERROR", uniqueId);
}
else {
formContext.ui.clearFormNotification(uniqueId);
formContext.data.entity.save();
}
// return true or false
resolve(isNotFound);
},
function (error) {
reject(error.message);
//console.log(error.message);
}
);
});
}
Hope this helps.