How to use jquery promise in JSOM

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
3
down vote

favorite












I have code like this (Default.aspx):



<asp:Label id="LabelA" runat="server" Text="0"></asp:Label> 
<script type="text/javascript">
document.getElementById('LabelA').innerHTML = getVerificheCount('ListTitle','StatusNotOk');
</script>


Code in App.js:



var verificheList;
var ctx = SP.ClientContext.get_current();
var hostWebURL = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
var verbaleList;
var statoVerifica;
var listTitle = '';
var countItems;

function getVerificheCount(title, stato)
statoVerifica = stato;
listTitle = title;
var hostWebContext = new SP.AppContextSite(ctx, hostWebURL);
verbaleList = hostWebContext.get_web().get_lists().getByTitle(listTitle);
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml(
'<View><Query><Where><Eq>' +
'<FieldRef Name='Verifica'/><Value Type='Choice'>' + stato + '</Value>' +
'</Eq></Where></Query></View>');
verificheList = verbaleList.getItems(camlQuery);
ctx.load(verificheList);
ctx.executeQueryAsync(function()
countItems = verificheList.get_count();
, onGetverificheListFail);
return countItems;



I'd like to use jquery promise, but where should I insert it?










share|improve this question





























    up vote
    3
    down vote

    favorite












    I have code like this (Default.aspx):



    <asp:Label id="LabelA" runat="server" Text="0"></asp:Label> 
    <script type="text/javascript">
    document.getElementById('LabelA').innerHTML = getVerificheCount('ListTitle','StatusNotOk');
    </script>


    Code in App.js:



    var verificheList;
    var ctx = SP.ClientContext.get_current();
    var hostWebURL = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
    var verbaleList;
    var statoVerifica;
    var listTitle = '';
    var countItems;

    function getVerificheCount(title, stato)
    statoVerifica = stato;
    listTitle = title;
    var hostWebContext = new SP.AppContextSite(ctx, hostWebURL);
    verbaleList = hostWebContext.get_web().get_lists().getByTitle(listTitle);
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml(
    '<View><Query><Where><Eq>' +
    '<FieldRef Name='Verifica'/><Value Type='Choice'>' + stato + '</Value>' +
    '</Eq></Where></Query></View>');
    verificheList = verbaleList.getItems(camlQuery);
    ctx.load(verificheList);
    ctx.executeQueryAsync(function()
    countItems = verificheList.get_count();
    , onGetverificheListFail);
    return countItems;



    I'd like to use jquery promise, but where should I insert it?










    share|improve this question

























      up vote
      3
      down vote

      favorite









      up vote
      3
      down vote

      favorite











      I have code like this (Default.aspx):



      <asp:Label id="LabelA" runat="server" Text="0"></asp:Label> 
      <script type="text/javascript">
      document.getElementById('LabelA').innerHTML = getVerificheCount('ListTitle','StatusNotOk');
      </script>


      Code in App.js:



      var verificheList;
      var ctx = SP.ClientContext.get_current();
      var hostWebURL = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
      var verbaleList;
      var statoVerifica;
      var listTitle = '';
      var countItems;

      function getVerificheCount(title, stato)
      statoVerifica = stato;
      listTitle = title;
      var hostWebContext = new SP.AppContextSite(ctx, hostWebURL);
      verbaleList = hostWebContext.get_web().get_lists().getByTitle(listTitle);
      var camlQuery = new SP.CamlQuery();
      camlQuery.set_viewXml(
      '<View><Query><Where><Eq>' +
      '<FieldRef Name='Verifica'/><Value Type='Choice'>' + stato + '</Value>' +
      '</Eq></Where></Query></View>');
      verificheList = verbaleList.getItems(camlQuery);
      ctx.load(verificheList);
      ctx.executeQueryAsync(function()
      countItems = verificheList.get_count();
      , onGetverificheListFail);
      return countItems;



      I'd like to use jquery promise, but where should I insert it?










      share|improve this question















      I have code like this (Default.aspx):



      <asp:Label id="LabelA" runat="server" Text="0"></asp:Label> 
      <script type="text/javascript">
      document.getElementById('LabelA').innerHTML = getVerificheCount('ListTitle','StatusNotOk');
      </script>


      Code in App.js:



      var verificheList;
      var ctx = SP.ClientContext.get_current();
      var hostWebURL = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
      var verbaleList;
      var statoVerifica;
      var listTitle = '';
      var countItems;

      function getVerificheCount(title, stato)
      statoVerifica = stato;
      listTitle = title;
      var hostWebContext = new SP.AppContextSite(ctx, hostWebURL);
      verbaleList = hostWebContext.get_web().get_lists().getByTitle(listTitle);
      var camlQuery = new SP.CamlQuery();
      camlQuery.set_viewXml(
      '<View><Query><Where><Eq>' +
      '<FieldRef Name='Verifica'/><Value Type='Choice'>' + stato + '</Value>' +
      '</Eq></Where></Query></View>');
      verificheList = verbaleList.getItems(camlQuery);
      ctx.load(verificheList);
      ctx.executeQueryAsync(function()
      countItems = verificheList.get_count();
      , onGetverificheListFail);
      return countItems;



      I'd like to use jquery promise, but where should I insert it?







      jquery jsom promises






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 2 hours ago









      helb

      471312




      471312










      asked 4 hours ago









      spiderman77

      1275




      1275




















          2 Answers
          2






          active

          oldest

          votes

















          up vote
          3
          down vote













          You don't necessarily need to use a promise here, just don't try to set the value of the HTML element until after you get your result.



          So in your default.aspx:



          <asp:Label id="LabelA" runat="server" Text="0"></asp:Label> 
          <script type="text/javascript">
          // just kick off the asynchronous call
          getVerificheCount('ListTitle','StatusNotOk');
          </script>


          And in your App.js:



          ctx.executeQueryAsync(function() 
          // now that you have your result, go ahead and set the value of the label
          document.getElementById('LabelA').innerHTML = verificheList.get_count();
          , onGetverificheListFail);
          // now you also don't need to return anything from this function
          // return countItems;


          One thing to watch out for - it's been a while since I've done stuff like this, but if I recall correctly, if you set your label to runat="server", the server is going to rewrite the id, so your document.getElementById('LabelA') might not work... right? Can anyone else confirm or deny what I'm saying about the ID rewriting?






          share|improve this answer




















          • Ok, I like your approach, because it is clear and simple... However the doubt is... What happen if the getVerificheCount function runs for X seconds? the page is blocked or not?
            – spiderman77
            57 mins ago






          • 1




            The page will not be blocked. executeQueryAsync is an asynchronous call.
            – Rob Windsor
            34 mins ago






          • 1




            To ensure the id of your label is LabelA you will either have to add the ClientIDMode="Static" attribute to the Label server control or replace the server control with a HTML element like a Span.
            – Rob Windsor
            30 mins ago










          • Thanks @RobWindsor, I didn't even know about the ClientIDMode="Static" option, I'll have to read up on that!
            – Dylan Cristy
            28 mins ago

















          up vote
          2
          down vote













          Here's an example of how to wrap a JSOM call in a jQuery promise. You should be able to modify the code above to use the same calling pattern.



          function getListsCsomJquery(rowLimit) 
          var dfd = jQuery.Deferred();

          var context = SP.ClientContext.get_current();
          var web = context.get_web();
          var lists = web.get_lists();
          var listsArray = context.loadQuery(lists);
          context.executeQueryAsync(success, fail);

          function success()
          dfd.resolve(listsArray.slice(0, rowLimit));


          function fail(sender, args)
          dfd.reject( responseText: args.get_message() );


          return dfd.promise();


          function jqueryCsomButtonClick()
          var message = container.find("#message");

          var call = getListsCsomJquery(10);
          call.done(function (data)
          message.text("Lists:");
          data.forEach(function (list)
          message.append("<br/>");
          message.append(list.get_title());
          );
          );
          call.fail(function (errorObject)
          message.text(errorObject.responseText);
          );

          message.text("Waiting for result...");






          share|improve this answer




















            Your Answer







            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "232"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            convertImagesToLinks: false,
            noModals: false,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













             

            draft saved


            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsharepoint.stackexchange.com%2fquestions%2f250324%2fhow-to-use-jquery-promise-in-jsom%23new-answer', 'question_page');

            );

            Post as a guest






























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            3
            down vote













            You don't necessarily need to use a promise here, just don't try to set the value of the HTML element until after you get your result.



            So in your default.aspx:



            <asp:Label id="LabelA" runat="server" Text="0"></asp:Label> 
            <script type="text/javascript">
            // just kick off the asynchronous call
            getVerificheCount('ListTitle','StatusNotOk');
            </script>


            And in your App.js:



            ctx.executeQueryAsync(function() 
            // now that you have your result, go ahead and set the value of the label
            document.getElementById('LabelA').innerHTML = verificheList.get_count();
            , onGetverificheListFail);
            // now you also don't need to return anything from this function
            // return countItems;


            One thing to watch out for - it's been a while since I've done stuff like this, but if I recall correctly, if you set your label to runat="server", the server is going to rewrite the id, so your document.getElementById('LabelA') might not work... right? Can anyone else confirm or deny what I'm saying about the ID rewriting?






            share|improve this answer




















            • Ok, I like your approach, because it is clear and simple... However the doubt is... What happen if the getVerificheCount function runs for X seconds? the page is blocked or not?
              – spiderman77
              57 mins ago






            • 1




              The page will not be blocked. executeQueryAsync is an asynchronous call.
              – Rob Windsor
              34 mins ago






            • 1




              To ensure the id of your label is LabelA you will either have to add the ClientIDMode="Static" attribute to the Label server control or replace the server control with a HTML element like a Span.
              – Rob Windsor
              30 mins ago










            • Thanks @RobWindsor, I didn't even know about the ClientIDMode="Static" option, I'll have to read up on that!
              – Dylan Cristy
              28 mins ago














            up vote
            3
            down vote













            You don't necessarily need to use a promise here, just don't try to set the value of the HTML element until after you get your result.



            So in your default.aspx:



            <asp:Label id="LabelA" runat="server" Text="0"></asp:Label> 
            <script type="text/javascript">
            // just kick off the asynchronous call
            getVerificheCount('ListTitle','StatusNotOk');
            </script>


            And in your App.js:



            ctx.executeQueryAsync(function() 
            // now that you have your result, go ahead and set the value of the label
            document.getElementById('LabelA').innerHTML = verificheList.get_count();
            , onGetverificheListFail);
            // now you also don't need to return anything from this function
            // return countItems;


            One thing to watch out for - it's been a while since I've done stuff like this, but if I recall correctly, if you set your label to runat="server", the server is going to rewrite the id, so your document.getElementById('LabelA') might not work... right? Can anyone else confirm or deny what I'm saying about the ID rewriting?






            share|improve this answer




















            • Ok, I like your approach, because it is clear and simple... However the doubt is... What happen if the getVerificheCount function runs for X seconds? the page is blocked or not?
              – spiderman77
              57 mins ago






            • 1




              The page will not be blocked. executeQueryAsync is an asynchronous call.
              – Rob Windsor
              34 mins ago






            • 1




              To ensure the id of your label is LabelA you will either have to add the ClientIDMode="Static" attribute to the Label server control or replace the server control with a HTML element like a Span.
              – Rob Windsor
              30 mins ago










            • Thanks @RobWindsor, I didn't even know about the ClientIDMode="Static" option, I'll have to read up on that!
              – Dylan Cristy
              28 mins ago












            up vote
            3
            down vote










            up vote
            3
            down vote









            You don't necessarily need to use a promise here, just don't try to set the value of the HTML element until after you get your result.



            So in your default.aspx:



            <asp:Label id="LabelA" runat="server" Text="0"></asp:Label> 
            <script type="text/javascript">
            // just kick off the asynchronous call
            getVerificheCount('ListTitle','StatusNotOk');
            </script>


            And in your App.js:



            ctx.executeQueryAsync(function() 
            // now that you have your result, go ahead and set the value of the label
            document.getElementById('LabelA').innerHTML = verificheList.get_count();
            , onGetverificheListFail);
            // now you also don't need to return anything from this function
            // return countItems;


            One thing to watch out for - it's been a while since I've done stuff like this, but if I recall correctly, if you set your label to runat="server", the server is going to rewrite the id, so your document.getElementById('LabelA') might not work... right? Can anyone else confirm or deny what I'm saying about the ID rewriting?






            share|improve this answer












            You don't necessarily need to use a promise here, just don't try to set the value of the HTML element until after you get your result.



            So in your default.aspx:



            <asp:Label id="LabelA" runat="server" Text="0"></asp:Label> 
            <script type="text/javascript">
            // just kick off the asynchronous call
            getVerificheCount('ListTitle','StatusNotOk');
            </script>


            And in your App.js:



            ctx.executeQueryAsync(function() 
            // now that you have your result, go ahead and set the value of the label
            document.getElementById('LabelA').innerHTML = verificheList.get_count();
            , onGetverificheListFail);
            // now you also don't need to return anything from this function
            // return countItems;


            One thing to watch out for - it's been a while since I've done stuff like this, but if I recall correctly, if you set your label to runat="server", the server is going to rewrite the id, so your document.getElementById('LabelA') might not work... right? Can anyone else confirm or deny what I'm saying about the ID rewriting?







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered 1 hour ago









            Dylan Cristy

            7,28921338




            7,28921338











            • Ok, I like your approach, because it is clear and simple... However the doubt is... What happen if the getVerificheCount function runs for X seconds? the page is blocked or not?
              – spiderman77
              57 mins ago






            • 1




              The page will not be blocked. executeQueryAsync is an asynchronous call.
              – Rob Windsor
              34 mins ago






            • 1




              To ensure the id of your label is LabelA you will either have to add the ClientIDMode="Static" attribute to the Label server control or replace the server control with a HTML element like a Span.
              – Rob Windsor
              30 mins ago










            • Thanks @RobWindsor, I didn't even know about the ClientIDMode="Static" option, I'll have to read up on that!
              – Dylan Cristy
              28 mins ago
















            • Ok, I like your approach, because it is clear and simple... However the doubt is... What happen if the getVerificheCount function runs for X seconds? the page is blocked or not?
              – spiderman77
              57 mins ago






            • 1




              The page will not be blocked. executeQueryAsync is an asynchronous call.
              – Rob Windsor
              34 mins ago






            • 1




              To ensure the id of your label is LabelA you will either have to add the ClientIDMode="Static" attribute to the Label server control or replace the server control with a HTML element like a Span.
              – Rob Windsor
              30 mins ago










            • Thanks @RobWindsor, I didn't even know about the ClientIDMode="Static" option, I'll have to read up on that!
              – Dylan Cristy
              28 mins ago















            Ok, I like your approach, because it is clear and simple... However the doubt is... What happen if the getVerificheCount function runs for X seconds? the page is blocked or not?
            – spiderman77
            57 mins ago




            Ok, I like your approach, because it is clear and simple... However the doubt is... What happen if the getVerificheCount function runs for X seconds? the page is blocked or not?
            – spiderman77
            57 mins ago




            1




            1




            The page will not be blocked. executeQueryAsync is an asynchronous call.
            – Rob Windsor
            34 mins ago




            The page will not be blocked. executeQueryAsync is an asynchronous call.
            – Rob Windsor
            34 mins ago




            1




            1




            To ensure the id of your label is LabelA you will either have to add the ClientIDMode="Static" attribute to the Label server control or replace the server control with a HTML element like a Span.
            – Rob Windsor
            30 mins ago




            To ensure the id of your label is LabelA you will either have to add the ClientIDMode="Static" attribute to the Label server control or replace the server control with a HTML element like a Span.
            – Rob Windsor
            30 mins ago












            Thanks @RobWindsor, I didn't even know about the ClientIDMode="Static" option, I'll have to read up on that!
            – Dylan Cristy
            28 mins ago




            Thanks @RobWindsor, I didn't even know about the ClientIDMode="Static" option, I'll have to read up on that!
            – Dylan Cristy
            28 mins ago












            up vote
            2
            down vote













            Here's an example of how to wrap a JSOM call in a jQuery promise. You should be able to modify the code above to use the same calling pattern.



            function getListsCsomJquery(rowLimit) 
            var dfd = jQuery.Deferred();

            var context = SP.ClientContext.get_current();
            var web = context.get_web();
            var lists = web.get_lists();
            var listsArray = context.loadQuery(lists);
            context.executeQueryAsync(success, fail);

            function success()
            dfd.resolve(listsArray.slice(0, rowLimit));


            function fail(sender, args)
            dfd.reject( responseText: args.get_message() );


            return dfd.promise();


            function jqueryCsomButtonClick()
            var message = container.find("#message");

            var call = getListsCsomJquery(10);
            call.done(function (data)
            message.text("Lists:");
            data.forEach(function (list)
            message.append("<br/>");
            message.append(list.get_title());
            );
            );
            call.fail(function (errorObject)
            message.text(errorObject.responseText);
            );

            message.text("Waiting for result...");






            share|improve this answer
























              up vote
              2
              down vote













              Here's an example of how to wrap a JSOM call in a jQuery promise. You should be able to modify the code above to use the same calling pattern.



              function getListsCsomJquery(rowLimit) 
              var dfd = jQuery.Deferred();

              var context = SP.ClientContext.get_current();
              var web = context.get_web();
              var lists = web.get_lists();
              var listsArray = context.loadQuery(lists);
              context.executeQueryAsync(success, fail);

              function success()
              dfd.resolve(listsArray.slice(0, rowLimit));


              function fail(sender, args)
              dfd.reject( responseText: args.get_message() );


              return dfd.promise();


              function jqueryCsomButtonClick()
              var message = container.find("#message");

              var call = getListsCsomJquery(10);
              call.done(function (data)
              message.text("Lists:");
              data.forEach(function (list)
              message.append("<br/>");
              message.append(list.get_title());
              );
              );
              call.fail(function (errorObject)
              message.text(errorObject.responseText);
              );

              message.text("Waiting for result...");






              share|improve this answer






















                up vote
                2
                down vote










                up vote
                2
                down vote









                Here's an example of how to wrap a JSOM call in a jQuery promise. You should be able to modify the code above to use the same calling pattern.



                function getListsCsomJquery(rowLimit) 
                var dfd = jQuery.Deferred();

                var context = SP.ClientContext.get_current();
                var web = context.get_web();
                var lists = web.get_lists();
                var listsArray = context.loadQuery(lists);
                context.executeQueryAsync(success, fail);

                function success()
                dfd.resolve(listsArray.slice(0, rowLimit));


                function fail(sender, args)
                dfd.reject( responseText: args.get_message() );


                return dfd.promise();


                function jqueryCsomButtonClick()
                var message = container.find("#message");

                var call = getListsCsomJquery(10);
                call.done(function (data)
                message.text("Lists:");
                data.forEach(function (list)
                message.append("<br/>");
                message.append(list.get_title());
                );
                );
                call.fail(function (errorObject)
                message.text(errorObject.responseText);
                );

                message.text("Waiting for result...");






                share|improve this answer












                Here's an example of how to wrap a JSOM call in a jQuery promise. You should be able to modify the code above to use the same calling pattern.



                function getListsCsomJquery(rowLimit) 
                var dfd = jQuery.Deferred();

                var context = SP.ClientContext.get_current();
                var web = context.get_web();
                var lists = web.get_lists();
                var listsArray = context.loadQuery(lists);
                context.executeQueryAsync(success, fail);

                function success()
                dfd.resolve(listsArray.slice(0, rowLimit));


                function fail(sender, args)
                dfd.reject( responseText: args.get_message() );


                return dfd.promise();


                function jqueryCsomButtonClick()
                var message = container.find("#message");

                var call = getListsCsomJquery(10);
                call.done(function (data)
                message.text("Lists:");
                data.forEach(function (list)
                message.append("<br/>");
                message.append(list.get_title());
                );
                );
                call.fail(function (errorObject)
                message.text(errorObject.responseText);
                );

                message.text("Waiting for result...");







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered 1 hour ago









                Rob Windsor

                9,3981736




                9,3981736



























                     

                    draft saved


                    draft discarded















































                     


                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsharepoint.stackexchange.com%2fquestions%2f250324%2fhow-to-use-jquery-promise-in-jsom%23new-answer', 'question_page');

                    );

                    Post as a guest













































































                    Comments

                    Popular posts from this blog

                    Long meetings (6-7 hours a day): Being “babysat” by supervisor

                    What does second last employer means? [closed]

                    One-line joke