在Promise内过滤数组元素:currentBillCyclePath作用域异常问题
Solution: Fix Scope Issue and Implement Filter Logic
First, let's address the scope concern with currentBillCyclePath: since it's a parameter to your GetRelatedBillingDocumentsFromList function, it should be accessible within the .then() callback closure. If it was appearing undefined, it's likely due to a typo, accidental variable shadowing, or the value being modified elsewhere before the callback executes. We'll ensure we use it correctly in the filter logic below.
Next, let's implement the filter to exclude items where the 4th segment of FileRef matches currentBillCyclePath:
Revised Code Snippet
Here's the updated version of your function with the filter logic added, plus fixes for other minor issues:
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); var camlQuery = '<View Scope="RecursiveAll">' + viewFields + '<Query>' + '<Where>' + '<And>' + '<Eq>' + '<FieldRef Name="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(); while (enumerator.moveNext()) { var listItem = enumerator.get_current(); var listItemValues = {}; // Fixed: initialized as object instead of array selectProperties.forEach(function(propertyName) { var value = listItem.get_item(propertyName); if(propertyName === "JobCodesMulti"){ var jobvalue = ""; // Fixed: declared var to avoid global scope value.forEach(function(jobvalues){ jobvalue+= jobvalues.get_lookupValue() +";"; }) listItemValues[propertyName] = jobvalue; } else { listItemValues[propertyName] = value; } }); // Add filter logic here if (listItemValues.FileRef) { var pathSegments = listItemValues.FileRef.split("/"); // Get 4th index (0-based array) var itemBillCyclePath = pathSegments[4]; // Only add if it doesn't match currentBillCyclePath if (itemBillCyclePath !== currentBillCyclePath) { listItemsWithValues.push(listItemValues); } } } var promises = listItemsWithValues.map(addContentType); $q.all(promises).then(youCanUseTheData); function youCanUseTheData(){ 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"]; var arrayofstrings = parentLink.split("/"); // Fixed: declared var var billCycleFolderName = arrayofstrings[arrayofstrings.length-2]; arrayofstrings.pop(); var hyperLink = '<a href="' + arrayofstrings.join('/') + '">' + billCycleFolderName + '</a>'; listItem["Bill Cycle"] = hyperLink; // Fixed: Set Document Type on the individual listItem, not the array listItem["Document Type"] = getContentTypeOfCurrentItem(listItem.ID.toString()); }); var enhancedListItemValues = spService.SpSearchQuery.EnhanceSearchResults(listItemsWithValues, enhanceFunctions); deferred.resolve(listItemsWithValues); } } }) .catch (function (message) { $log.error("Error retrieving billing documents: " + message); // Added error logging deferred.reject(message); // Pass error to reject }); return deferred.promise; }
Key Changes Made:
- Filter Logic: Added a check before pushing
listItemValuesto the array. We splitFileRefto get the 4th segment and compare it tocurrentBillCyclePath—only non-matching items are added. - Fixed Variable Initialization: Changed
var listItemValues = [];tovar listItemValues = {};since it's storing key-value pairs, not an array. - Avoided Global Variables: Declared
jobvalueandarrayofstringswithvarto prevent them from leaking into global scope. - Corrected Document Type Assignment: Set
listItem["Document Type"]instead oflistItemsWithValues["Document Type"](sincelistItemsWithValuesis an array, not an object). - Improved Error Handling: Added logging to the
.catch()block and passed the error message todeferred.reject().
Additional Notes:
- If
currentBillCyclePathis still appearing undefined in the callback, double-check that the parameter is being passed correctly from theGetDatafunction. Ensure there's no typo in the variable name (case sensitivity matters in JavaScript). - Verify that
FileRefis always present in the list items—our code includes a check to avoid errors if it's missing.
内容的提问来源于stack exchange,提问作者Luis Valencia
相关产品推荐
相关产品推荐

