0

In the example below, the first alert will print whereas the second one will not. I need to use ctx.executeQueryAsync to perform a number of operations, but I need to use the updated value of "titles" after this is ran. If I try it afterwards, the console says that "titles" is undefined or blank. I have been able to update variables in for loops throughout the rest of the code, and this is the remaining piece.

This is being used on a SharePoint list by the way.

function doStuff() {
    var titles = [];
    for(var i = 0; i < selectedItems.length; i++) {
        var id = selectedItems[i].id;
        var item = list.getItemById(id);
        items.push(item);
        ctx.load(item, "Title");
    }
    if (items) {
        ctx.executeQueryAsync(function() {

            for(var j = 0; j < items.length; j++) {
                titles.push(items[j].get_item("Title"));
            }
            alert(titles.toString());
        }, function(sender, args){
            alert('Request failed. ' 
                + args.get_message() + '\n' 
                + args.get_stackTrace());
        });
    }
    alert('titles '+titles.toString());
    }
Blazemonger
  • 90,923
  • 26
  • 142
  • 180
user3299197
  • 115
  • 6
  • "async" means "asynchronous", meaning that it won't ever be completed at the same time as the rest of your code. See https://learn.jquery.com/ajax/key-concepts/ – Blazemonger Mar 10 '14 at 18:54
  • possible duplicate of [jQuery ajax success anonymous function scope](http://stackoverflow.com/questions/1457690/jquery-ajax-success-anonymous-function-scope) – Blazemonger Mar 10 '14 at 18:57
  • Can I just add "async: false, " (I know it's not recommended, but I'm on a time crunch for the time being) inside the function? – user3299197 Mar 10 '14 at 19:02
  • Same as the others: you have to use async and adapt your code with it. The Microsoft API is a bit difficult to deal with. You may want to check out the API I created: http://aymkdn.github.io/SharepointPlus/ -- I think it's a bit easier to use :-) – AymKdn Mar 11 '14 at 09:42

1 Answers1

0
function doStuff() {
    var titles = [];
    for(var i = 0; i < selectedItems.length; i++) {
        var id = selectedItems[i].id;
        var item = list.getItemById(id);
        items.push(item);
        ctx.load(item, "Title");
    }
    if (items) {
        ctx.executeQueryAsync(function(titles) {
            return function() {
                for(var j = 0; j < items.length; j++) {
                    titles.push(items[j].get_item("Title"));
                }
                alert(titles.toString());
            }, function(sender, args){
                alert('Request failed. '
                    + args.get_message() + '\n'
                    + args.get_stackTrace());
            }
        }(titles));
    }
    alert('titles '+titles.toString());
}
spassvogel
  • 3,479
  • 2
  • 18
  • 23