Sunday, 26 March 2017

Run executeQueryAsync() synchronously SharePoint 2013

In JSOM, to fetch the data from the server we make a call through executeQueryAsync(). This works asynchronously by default.We need to make executeQueryAsync() behave synchronously.

That means we have to make this function wait till the operation gets completed and should return some values , then proceed to the next function.

This can be done by using JavaScript callbacks and deferred/Promises.
The promises pattern significantly simplifies JavaScript code when you make an app, which has multiple, nested asynchronous calls and it makes it very powerful.



<script type="text/javascript">
    var camlValues;
    $(document).ready(function () {
             
        SP.SOD.executeFunc('sp.js', 'SP.ClientContext', getItems);
    });
 
    function getItems() {
        getListItem('Test list').done(function()
{
        console.log(“Second Console Pass”);  
}).fail(function()
{
 console.log(“Second Console Fail”);  
});            
    }
 
    function getListItem(listTitle) {

      var deferred=$.Deferred();
        var clientContext = new SP.ClientContext.get_current();
        var olist = clientContext.get_web().get_lists().getByTitle(listTitle);
        var camlQuery = new SP.CamlQuery();
        ocamlItems = olist.getItems(camlQuery);
        clientContext.load(camlValues);
        clientContext.executeQueryAsync(
            Function.createDelegate(this, this.success),
            Function.createDelegate(this, this.failure)
        );

return deferred.promise();
    };
 
    function success(sender, args) {
        var listItemEnumerator = ocamlItems.getEnumerator();
        while (listItemEnumerator.moveNext()) {
            var olistItem = listItemEnumerator.get_current();
console.log(‘First Console Pass ‘);
             
deferred.resolve(olistItem );
        }
    }
 
    function onQueryFailed(sender, args) {
        console.log('An error occured while retrieving list items:' + args.get_message());

deferred.reject(olistItem );
    }
</script>





For the code given above, we will get the output, as shown below.

First Console Pass
Second Console Pass


Thanks.. Happy Coding..

No comments:

Post a Comment