-3

I have the following code which reads information from a sharepoint list and renders fine in google chrome, but when tested in IE 11 (Corporate Browser), then I get the following exception:

ReferenceError: 'Promise' is undefined
   at getContentTypeOfCurrentItem (https://ourserver.com/sites/billing/Style%20Library/xxx/Angular/related-billing-documents-controller.js:209:5)
   at addContentType (https://ourserver.com/sites/billing/Style.com/sites/billing/Style%20Library/xxx/Angular/related-billing-documents-controller.js:201:5)
   at Anonymous function (https://ourserver.com/sites/billing/Style%20Library/xxx/Angular/related-billing-documents-controller.js:163:7)
   at Anonymous function (https://ourserver.com/sites/billing/Style%20Library/xxx/Angular/angular.min.js:130:399)
   at m.prototype.$eval (https://ourserver.com/sites/billing/Style%20Library/xxx/Angular/angular.min.js:145:96)
   at m.prototype.$digest (https://ourserver.com/sites/billing/Style%20Library/xxx/Angular/angular.min.js:142:165)
   at Anonymous function (https://ourserver.com/sites/billing/Style%20Library/xxx




(function () {
    angular
    .module('BillCycleApp')
    .controller('relatedBillingDocumentsController', ['$scope', '$log', '$q', 'spService', 'BillingDocuments', 'General',
        function ($scope, $log, $q, spService, config, generalConfig) {

            var vm = this;              
            var tableSelector = "#related-billing-documents-table";
            var componentSelector = ".related-billing-documents";

            function GetContext() {                 
                vm.Name = config.Name;                  
                var dataTableColumns = spService.TransformFieldsToDataTableColumns(config.FieldsToShow);                    
                $.fn.dataTable.moment( generalConfig.DateTimeFormat );
                // Initialize with empty data
                $(tableSelector).DataTable({
                    data : [],
                    columns : dataTableColumns,
                    order : config.SortOrder,
                    deferRender : true
                }).on( 'draw.dt', function ( e, settings, processing ) {
                    // Make sure the UserPresence is added every time the DataTable's data changes (paging, sorting, search,..)
                    spService.UserPresenceComponent.AddPresence();
                });
                // Make component visible
                $(componentSelector).css("visibility", "visible");

                // SP.js function
                // Get Bill Cycle list & id
                var listItemId = GetUrlKeyValue('ID', true, window.location.search, true);
                var listId = "{" + GetUrlKeyValue('List', true, window.location.search, true) + "}";                    
                var propertiesToLoad = ["FileRef","PwC_ClientCode","PwC_JobCodesMulti","PwC_EngagementCode"];
                spService.GetListItem(listId, listItemId, propertiesToLoad)
                .then(function(billCycle) {
                        var listItemValues = [];                            
                        propertiesToLoad
                        .forEach(function(propertyName) {
                            var value = billCycle.get_item(propertyName);
                            listItemValues[propertyName] = value;
                        });

                        var billCyclePath = _spPageContextInfo.siteAbsoluteUrl;
                        billCyclePath += listItemValues["FileRef"];
                        var clientCode = listItemValues["PwC_ClientCode"]
                        var jobCodesLookups = listItemValues["PwC_JobCodesMulti"];
                        var engagementCode = listItemValues["PwC_EngagementCode"]
                        var jobCodes = [];
                        if(jobCodesLookups) {                               
                            jobCodesLookups.forEach(function(lookup) {
                                jobCodes.push(lookup.get_lookupValue());
                            });
                        }
                        // Get data with parameters
                        GetData(billCyclePath, clientCode, jobCodes, engagementCode);

                });
            }

            function GetData(billCyclePath, clientCode, jobCodes, engagementCode) {             
                var enhanceFunctions = [
                    function(searchResultRow) {
                        return spService.AddHyperLinkOnFields(searchResultRow, config.HyperLinks);
                    },
                    function(searchResultRow) {
                        return spService.AddPresenceOnFields(searchResultRow, config.UserFields);
                    },
                    function(searchResultRow) {
                        return spService.FormatDateFields(searchResultRow, config.DateFields, generalConfig.DateTimeFormat);
                    },
                    function(searchResultRow) {
                        return spService.AddImageMapping(searchResultRow, config.ImageFields);
                    },
                    function(searchResultRow) {
                        return spService.FormatNumberFields(searchResultRow, config.NumberFields);
                    },
                    function(searchResultRow) {
                        // Put link to parent Bill Cycle with name = folder name
                        //var parentLink = searchResultRow["FileRef"];
                        //arrayofstrings = parentLink.split("/");
                        //var billCycleFolderName = arrayofstrings[arrayofstrings.length-2];
                        //arrayofstrings.pop();
                        //var hyperLink = '<a href="' + arrayofstrings.join('/') + '">' + billCycleFolderName + '</a>';                         
                        //searchResultRow["Bill Cycle"] = hyperLink; 
                    }
                ];

                // Get data from SP             
                var selectProperties = spService.TransformFieldsToSelectProperties(config.Fields); // copy array
                var selectPropertiesToShow = spService.TransformFieldsToSelectProperties(config.FieldsToShow); // copy array

                var extendedSelectProperties = selectProperties.slice();
                var hyperLinkedProperties = spService.TransformFieldsToSelectProperties(config.HyperLinks)
                extendedSelectProperties = extendedSelectProperties.concat(hyperLinkedProperties);

                GetRelatedBillingDocumentsFromList(extendedSelectProperties, billCyclePath, clientCode, jobCodes, engagementCode, enhanceFunctions)
                .then(function (data) {
                    var trimmedData = spService.SpSearchQuery.TrimSearchResultsToSelectProperties(data, selectPropertiesToShow);
                    // Add data to dataTable
                    var dataTable = $(tableSelector).DataTable();
                    dataTable.clear().rows.add(trimmedData).columns.adjust().draw(); // Resize columns based on new data sizes                                          
                    vm.ValidDataLoaded = true;
                })
                .catch (function (message) {
                    vm.Name = "Error";
                    vm.ValidDataLoaded = true;
                });

            }

            function GetRelatedBillingDocumentsFromList(selectProperties, currentBillCyclePath, clientCode, jobCodes, engagementCode, enhanceFunctions) {
                $log.info("Retrieving related billing documents for bill cycle with name [" + currentBillCyclePath + "]");                  
                var deferred = $q.defer();
                var webUrl = _spPageContextInfo.webAbsoluteUrl;

                selectProperties = selectProperties.concat("ContentTypeId");
                var viewFields = spService.ConvertSelectPropertiesToViewFields(selectProperties);
                // query must return the documents for the same client but in other bill cycles not the current one
                var camlQuery = '<View Scope="RecursiveAll">' +   viewFields + 
                        '<Query>' +
                            '<Where>' +
                                '<And>' +
                                    '<Eq>' +
                                        '<FieldRef Name="PwC_ClientCode" />' +
                                        '<Value Type="Text">'+ clientCode + '</Value>' +
                                    '</Eq>' +
                                    '<Neq>' +
                                        '<FieldRef Name="ContentType" />' +
                                        '<Value Type="Computed">Bill Cycle</Value>' +
                                    '</Neq>' +
                                '</And>' +
                            '</Where>' +
                        '</Query>' +
                    '</View>';

                var billCyclesListId = "{c23bbae4-34f7-494c-8f67-acece3ba60da}";                    
                spService.GetListItems(billCyclesListId, camlQuery, selectProperties)
                .then(function(listItems) {                 
                    var listItemsWithValues = [];

                    if(listItems) {
                        var enumerator = listItems.getEnumerator();
                        var promises = [];
                        while (enumerator.moveNext()) {
                            var listItem = enumerator.get_current();
                            var listItemValues = [];                                
                            selectProperties
                            .forEach(function(propertyName) {                               
                                var value = listItem.get_item(propertyName);
                                if(propertyName === "PwC_JobCodesMulti"){
                                    jobvalue = "";
                                    value.forEach(function(jobvalues){
                                        jobvalue+= jobvalues.get_lookupValue() +";";
                                    })
                                    listItemValues[propertyName] = jobvalue;
                                }else{
                                    listItemValues[propertyName] = value;
                                }   
                            });

                            listItemsWithValues.push(listItemValues);
                        }

                        var promises = listItemsWithValues.map(addContentType);
                        Promise.all(promises).then(youCanUseTheData);

                        function youCanUseTheData(){
                            /*
                            At this point, each listItem holds the 'Document Type' info
                            */
                            listItemsWithValues.forEach(function(listItem) {
                                var fileDirRef = listItem["FileRef"];
                                var id = listItem["ID"];
                                var title = listItem["Title"];
                                var serverUrl = _spPageContextInfo.webAbsoluteUrl.replace(_spPageContextInfo.webServerRelativeUrl,"");                          
                                var dispFormUrl = serverUrl + "/sites/billing/_layouts/15/DocSetHome.aspx?id="+fileDirRef;
                                var parentLink = listItem["FileRef"];
                                arrayofstrings = parentLink.split("/");
                                var billCycleFolderName = arrayofstrings[arrayofstrings.length-2];
                                arrayofstrings.pop();
                                var hyperLink = '<a href="' + arrayofstrings.join('/') + '">' + billCycleFolderName + '</a>';                           
                                listItem["Bill Cycle"] = hyperLink; 
                                listItemsWithValues["Document Type"] = getContentTypeOfCurrentItem(listItem.ID.toString());
                            });

                            var enhancedListItemValues = spService.SpSearchQuery.EnhanceSearchResults(listItemsWithValues, enhanceFunctions);                       
                            deferred.resolve(listItemsWithValues);
                        }
                    }   

                })
                .catch (function (message) {
                    deferred.reject();
                });

                return deferred.promise;
            }


            function addContentType(listItem){
                //return getContentTypeOfCurrentItem(listItem.ID.toString());
                return getContentTypeOfCurrentItem(listItem.ID.toString()).then(function(cname) {
                    listItem['Document Type'] = cname; //we add the doc type to each listItem, not only the last one
                }).catch(function(error) {
                    $log.warn("Server error");
                });
            }

            function getContentTypeOfCurrentItem(id) {
                return new Promise(function (resolve, reject) {
                    var clientContext = new SP.ClientContext.get_current();
                    var oList = clientContext.get_web().get_lists().getByTitle("Bill Cycles");
                    var listItem2 = oList.getItemById(id);
                    listContentTypes = oList.get_contentTypes();
                    clientContext.load(listContentTypes);
                    clientContext.load(listItem2, 'ContentTypeId');             
                    clientContext.executeQueryAsync(
                        function() {
                            $log.info("Successfully retrieved getContentTypeOfCurrentItemt");
                            var ctid = listItem2.get_item("ContentTypeId").toString();            
                            var ct_enumerator = listContentTypes.getEnumerator();
                            while (ct_enumerator.moveNext()) {
                                var ct = ct_enumerator.get_current();            
                                if (ct.get_id().toString() == ctid) {
                                    var contentTypeName = ct.get_name();
                                }
                            }
                            return resolve(contentTypeName);
                       },
                       function(error, errorInfo) {
                            $log.warn("Retrieving getContentTypeOfCurrentItem failed");
                            return reject(errorInfo);
                       }
                    );
                });
            }



            function GetRelatedBillingDocuments(selectProperties, currentBillCyclePath, clientCode, jobCodes, engagementCode, enhanceFunctions) {
                $log.info("Retrieving related billing documents for bill cycle with path [" + currentBillCyclePath + "]");
                var deferred = $q.defer();

                var webUrl = _spPageContextInfo.webAbsoluteUrl;

                // TODO: AND or OR?
                var jobCodesFilter = spService.ExpandSearchFilterForEachValue("JobCodes", ":", jobCodes, false, false);
                var engagementCodeFilter = "";
                if (engagementCode != undefined && engagementCode != "") {
                    engagementCodeFilter = "EngagementCode:" + engagementCode;
                }
                if(jobCodesFilter && engagementCodeFilter) {
                    jobCodesFilter += " OR ";
                }
                // TODO: Add use of result source?
                var queryText = "-Path:" + spService.AddQuotes(currentBillCyclePath) + ' AND -ContentType:"Bill Cycle" AND ClientCode:' + clientCode + " AND (" + jobCodesFilter + engagementCodeFilter + ")";

                var searchQuery = new spService.SpSearchQuery(webUrl, queryText, selectProperties, config.ResultSourceName, config.ResultSourceLevel);                      
                searchQuery
                .ExecuteSearchQueryFetchAll() // returns deferred           
                .then(function (results) {

                    $log.info("Successfully retrieved search results");
                    var searchResults = spService.SpSearchQuery.EnhanceSearchResults(results, enhanceFunctions);
                    deferred.resolve(searchResults);
                });

                return deferred.promise;
            }

            ExecuteOrDelayUntilScriptLoaded(GetContext, 'sp.js');
        }
    ]); // End Controller()
}()); // End IFFE
Luis Valencia
  • 32,619
  • 93
  • 286
  • 506
  • 1
    Well, IE 11 doesn't support promises. See [here](https://caniuse.com/#search=promise) – Federico klez Culloca Jan 16 '18 at 15:21
  • Promises aren't supported in IE: [MDN Promises Compat table](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#Browser_compatibility). Use a polyfill like Bluebird or q. – zero298 Jan 16 '18 at 15:21
  • why downvote? please explain. question is perfectly valid and the comments can be answers. – Luis Valencia Jan 16 '18 at 15:22
  • 2
    I didn't downvote you, but IMHO browser compatibility should have been one of the first things you should have checked before asking the question. – Federico klez Culloca Jan 16 '18 at 15:24
  • (_also_) you can do `$q.all(promises)` instead of `Promise.all(promises)` – Aleksey Solovey Jan 16 '18 at 15:27
  • and thats the only change? – Luis Valencia Jan 16 '18 at 15:35
  • `$q` resolves problem..yes and should always use it in angular apps anyway since it will tell angular to run digest if you change scope using it – charlietfl Jan 16 '18 at 15:42
  • 1
    I downvoted you because you have shown no research and you just dumped your code. You don't say what you have tried, or even googled. I mean googling "promise internet explorer" gives this question as the first result: [How to make promises work in IE11](https://stackoverflow.com/q/36016327/691711) which explains exactly what these comments are saying. You're a high rep user and I would expect that you would know how to make good questions. – zero298 Jan 16 '18 at 15:52
  • Possible duplicate of [How to make promises work in IE11](https://stackoverflow.com/questions/36016327/how-to-make-promises-work-in-ie11) – zero298 Jan 16 '18 at 15:53

1 Answers1

1

Promise is part of ES6 standard that is not fully supported by IE11, you can use babel-polyfill instead or use another librairy like q which is part of angularjs

Troopers
  • 5,127
  • 1
  • 37
  • 64