updating multiple list items in SharePoint with JavaScript without using promisses or other stuff

You maybe know the problem; you are updating or creating a set of items using the JSOM and the changes are made to only one item.
The  reason is that the process in the back (Event Receiver etc.) can handle only one item at the same time and if it takes to long it misses the update event for the other items. So you need to make sure the update waits until the update before is done. The deal is that the JSOM context works asynchronous. Some of you are using promisses or methods like that.
I made a solution that is working without any other library.

I have build a function that is getting an array of items and their values. The function is reading the first item in the array and starts an update. After the async call is done it deletes the item in the array and calls it self with the "new" array.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
function updateMultipleItemsInSequence(itemarray) {
    var listName = "List1";
    if (itemarray.length) {
        var context = new SP.ClientContext.get_current();
        var list = context.get_web().get_lists().getByTitle(listName);

        var listItem = list.getItemById(itemarray[0][0]);
        listItem.set_item('Field1', itemarray[0][1]);
        listItem.set_item('Field2', itemarray[0][2]);
        listItem.update();
        context.load(listItem);

        context.executeQueryAsync(Function.createDelegate(this, function () {
            itemarray.shift();
            updateMultipleItemsInSequence(itemarray);
        }), Function.createDelegate(this, function () {
            // stop.. error
        }));
    }
};

And thats how to call the function:

1
2
var itemArray = [[1, "value1", "value2"], [2, "value1", "value2"], [3, "value1", "value2"]];
updateMultipleItemsInSequence(itemArray);

I know this way is not the beautiest one, but it allows to call multiple updates without any additional library.

Comments

Popular posts from this blog

How to support multiple languages in WPF