1

I am performing looping in javascript for sharepoint. I want it to perform synchronously, means only after first data execution is done it should start with second. If first data execution is completed (whether it success or fail) then only it should start with second in each loop.

$.each(selectedSiteCollections, function (index, value) {              act.SharePoint.SharePointAppProgress.addStatusRow(act.Resources.StatusInfo.applyFolderNavigation, "applyFolderNavigationId");
                 var siteUrl = value;//_spPageContextInfo.siteServerRelativeUrl + "/" + projectUrl;
                 var  clientContext = act.SharePoint.SharePointAppCommon.getClientContext(siteUrl);
                 var newWebsite = clientContext.get_web();

                 var pageUrl = siteUrl + "/Shared%20Documents/Forms/AllItems.aspx";
                 var homePageUrl = siteUrl + "/Pages/Home.aspx";

                 var jsLinkUrl = '~siteCollection/_catalogs/masterpage/FolderNavigation.js'; //<-- specify JSLink url

                 var page = newWebsite.getFileByServerRelativeUrl(pageUrl);
                 var homePage = newWebsite.getFileByServerRelativeUrl(homePageUrl);



                 var wpm = page.getLimitedWebPartManager(SP.WebParts.PersonalizationScope.shared);
                 var collWebPart = wpm.get_webParts();

                 var wpmHome = homePage.getLimitedWebPartManager(SP.WebParts.PersonalizationScope.shared);
                 var collWebPartHome = wpmHome.get_webParts();

                 clientContext.load(homePage);
                 clientContext.load(collWebPart, 'Include(WebPart.Properties)');
                 clientContext.load(collWebPartHome, 'Include(WebPart.Properties)');

                 clientContext.executeQueryAsync(function () {
                     if (homePage.get_checkOutType() != SP.CheckOutType.online) {
                         homePage.checkOut();
                     }
                     var webPartDef = null;
                     for (var x = 0; x < collWebPart.get_count() && !webPartDef; x++) {
                         var temp = collWebPart.get_item(x);

                         webPartDef = temp;

                     }
                     if (webPartDef != null) {
                         var webpart = webPartDef.get_webPart();


                         var properties = webpart.get_properties();

                         properties.set_item('JSLink', jsLinkUrl);
                         webPartDef.saveWebPartChanges();
                     }


                     var webPartDefHome = null;
                     for (var x = 0; x < collWebPartHome.get_count() && !webPartDefHome; x++) {
                         var temp = collWebPartHome.get_item(x);

                         webPartDefHome = temp;

                     }
                     if (webPartDefHome != null) {
                         var webpart = webPartDefHome.get_webPart();


                         var properties = webpart.get_properties();

                         properties.set_item('JSLink', jsLinkUrl);
                         webPartDefHome.saveWebPartChanges();
                     }


                     homePage.checkIn("ACT Update webpart", SP.CheckinType.majorCheckIn);
                     homePage.publish("ACT Update webpart");
                     clientContext.executeQueryAsync(function () {

                         act.SharePoint.SharePointAppProgress.updateStatusRow(true, "applyFolderNavigationId");

                     }, function (sender, args) { executeAsyncFailed(sender, args, "applyFolderNavigationId"); });
                 }, function (sender, args) { executeAsyncFailed(sender, args, "applyFolderNavigationId"); });

             });
2

You can use JavaScript Callbacks or JQuery deferreds/Promises to work synchronously with JavaScript Client Object model:

Callback Example

$(document).ready(function () {
        //don't exectute any jsom until sp.js file has loaded.        
        SP.SOD.executeFunc('sp.js', 'SP.ClientContext', prepareTables);
    });

function prepareTables() {
    getItemsWithCaml('External User Account Request',
            function (camlItems) {
                var listItemEnumerator = camlItems.getEnumerator();
                while (listItemEnumerator.moveNext()) {
                    var listItem = listItemEnumerator.get_current();
                    console.log(listItem.get_item('Title'));
                } console.log('Completed table prparation.');
            },
            function (sender, args) {
                console.log('An error occured while retrieving list items:' + args.get_message());
            });
}    

function getItemsWithCaml(listTitle, success, error) {
    var clientContext = new SP.ClientContext.get_current();
    var list = clientContext.get_web().get_lists().getByTitle(listTitle);
    var camlQuery = new SP.CamlQuery();
    var camlItems = list.getItems(camlQuery);
    clientContext.load(camlItems);
    clientContext.executeQueryAsync(
            function () {
                success(camlItems);
            },
            error
        );
};

deferreds/Promises

$(document).ready(function () {
        //don't exectute any jsom until sp.js file has loaded.        
        SP.SOD.executeFunc('sp.js', 'SP.ClientContext', prepareTables);
    });    

function prepareTables() {
    getItemsWithCaml('External User Account Request').then(
            function (camlItems) {
                var listItemEnumerator = camlItems.getEnumerator();
                while (listItemEnumerator.moveNext()) {
                    var listItem = listItemEnumerator.get_current();
                    console.log(listItem.get_item('Title'));
                } console.log('Completed table prparation.');
            },
            function (sender, args) {
                console.log('An error occured while retrieving list items:' + args.get_message());
            }
        );   
}    

function getItemsWithCaml(listTitle) {
    //use of $.Deferred in the executeQueryAsync delegate allows the consumer of this method to write 'syncronous like' code
    var deferred = $.Deferred();
    var clientContext = new SP.ClientContext.get_current();
    var list = clientContext.get_web().get_lists().getByTitle(listTitle);
    var camlQuery = new SP.CamlQuery();        
    var items = list.getItems(camlQuery);
    clientContext.load(items);
    clientContext.executeQueryAsync(
        Function.createDelegate(this,
            function () { deferred.resolve(items); }),
        Function.createDelegate(this,
            function (sender, args) { deferred.reject(sender, args); }));

    return deferred.promise();
};

See Using deferreds/Promises Or Callbacks in Javascript client object model for more information

  • I have tried that but dint work !! as I have $each loop i guess – Mahesh Nov 19 '15 at 8:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.