Enumerating contents of 'context.load' JS object works but using 'getById' does not work
-
04-10-2020 - |
Вопрос
In my Office 365 App I have a simple functionality where it loads a library and then reads a couple of fields for all items in the library. Below is my sample code:
(function () {
$(document).ready(function () {
web = appContext.get_web();
pictureLib = web.get_lists().getByTitle(libraryTitle);
query = SP.CamlQuery.createAllItemsQuery();
allLibItems = pictureLib.getItems(query);
context.load(allLibItems, "Include(Id, Title, Description)");
context.executeQueryAsync(Function.createDelegate(this, onSuccess), Function.createDelegate(this, onFail));
});
function onSuccess() {
// Fetching by ID does NOT work
var pictureItem = allLibItems.getById(id);
console.log(pictureItem.get_item("Title")); // <-- Throws ERROR!
// Enumerating content works
var enumerator = allLibItems.getEnumerator();
while (enumerator.moveNext()) {
var pictureItem = enumerator.get_current();
console.log(pictureItem.get_item("Title")); // <-- This WORKS!
}
}
function onFail(sender, args) { /* Error handling code */ }
})();
I load the object of allLibItems
and then fetch individual list items from it.
The thing is, if I use var pictureItem = allLibItems.getById(id)
to fetch a particular item and use it like pictureItem.get_item("Title")
it throws error of:
Uncaught Error: The property or field has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.
But when I use var enumerator = allLibItems.getEnumerator()
and loop through the contents it works. Why?
Решение
I think the reason is that var pictureItem = allLibItems.getById(id);
returns a list item
, which needs to be loaded first and then executeQueryAsync
needs to be called to get the item details in success method.