How to use await with setTimeout and setInterval?












3















I have a function createSession for getting users with returned session object. createSession either returns users or throws string exception. My code is as follow, if session is successfull (which means I have users) continue code.



However I do not know when users are available because other resources also asks for it. So, I want a modify my code that it will try getting users in a timeout, lest say try it every 1 second until timeout 30 seconds reached.



async function callTest() {
const capabilities = {
type: {
chrome: 2
}
}

var session = await working.createSession(capabilities)

if(!session) return
callTest()

// remaining code goes here
}


I though to use setTimout in a promise but the problem is I can not use await inside a normal function. Can someone help me fixing my code ?



var checkAuth = function(capabilities) {
return new Promise(function(resolve) {

var id = setInterval(function() {
var session = await working.createSession(capabilities)

if (session) {
clearInterval(id);
resolve(id);
}
});
}, 10);
});
}









share|improve this question





























    3















    I have a function createSession for getting users with returned session object. createSession either returns users or throws string exception. My code is as follow, if session is successfull (which means I have users) continue code.



    However I do not know when users are available because other resources also asks for it. So, I want a modify my code that it will try getting users in a timeout, lest say try it every 1 second until timeout 30 seconds reached.



    async function callTest() {
    const capabilities = {
    type: {
    chrome: 2
    }
    }

    var session = await working.createSession(capabilities)

    if(!session) return
    callTest()

    // remaining code goes here
    }


    I though to use setTimout in a promise but the problem is I can not use await inside a normal function. Can someone help me fixing my code ?



    var checkAuth = function(capabilities) {
    return new Promise(function(resolve) {

    var id = setInterval(function() {
    var session = await working.createSession(capabilities)

    if (session) {
    clearInterval(id);
    resolve(id);
    }
    });
    }, 10);
    });
    }









    share|improve this question



























      3












      3








      3








      I have a function createSession for getting users with returned session object. createSession either returns users or throws string exception. My code is as follow, if session is successfull (which means I have users) continue code.



      However I do not know when users are available because other resources also asks for it. So, I want a modify my code that it will try getting users in a timeout, lest say try it every 1 second until timeout 30 seconds reached.



      async function callTest() {
      const capabilities = {
      type: {
      chrome: 2
      }
      }

      var session = await working.createSession(capabilities)

      if(!session) return
      callTest()

      // remaining code goes here
      }


      I though to use setTimout in a promise but the problem is I can not use await inside a normal function. Can someone help me fixing my code ?



      var checkAuth = function(capabilities) {
      return new Promise(function(resolve) {

      var id = setInterval(function() {
      var session = await working.createSession(capabilities)

      if (session) {
      clearInterval(id);
      resolve(id);
      }
      });
      }, 10);
      });
      }









      share|improve this question
















      I have a function createSession for getting users with returned session object. createSession either returns users or throws string exception. My code is as follow, if session is successfull (which means I have users) continue code.



      However I do not know when users are available because other resources also asks for it. So, I want a modify my code that it will try getting users in a timeout, lest say try it every 1 second until timeout 30 seconds reached.



      async function callTest() {
      const capabilities = {
      type: {
      chrome: 2
      }
      }

      var session = await working.createSession(capabilities)

      if(!session) return
      callTest()

      // remaining code goes here
      }


      I though to use setTimout in a promise but the problem is I can not use await inside a normal function. Can someone help me fixing my code ?



      var checkAuth = function(capabilities) {
      return new Promise(function(resolve) {

      var id = setInterval(function() {
      var session = await working.createSession(capabilities)

      if (session) {
      clearInterval(id);
      resolve(id);
      }
      });
      }, 10);
      });
      }






      javascript async-await






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Feb 5 '18 at 8:09









      Tomasz Mularczyk

      14.3k857100




      14.3k857100










      asked Feb 5 '18 at 8:00









      Rasim AVCIRasim AVCI

      50110




      50110
























          1 Answer
          1






          active

          oldest

          votes


















          1














          You can try to use it like this and it should work well



          var checkAuth = function(capabilities) {
          return new Promise(function(resolve) {
          setInterval(async function() {
          var session = await working.createSession(capabilities)
          if (session) {
          clearInterval(id);
          resolve(id);
          }
          }, 10);
          });
          }


          You should add async keyword to function definition in setInterval, because await can only work in async functions.
          Update: also move ,10 parameter from Promise definition to setInterval one






          share|improve this answer





















          • 1





            You should explain what you changed and why it is ok to make that change.

            – Felix Kling
            Feb 5 '18 at 8:26






          • 2





            Functions need to be async to be allowed to await things.

            – Jesper
            Feb 5 '18 at 8:28











          • your , 10 argument will be passed to the new Promise() constructor. And there should probably be a note about the fact that setInterval will not wait for its inner code to finish before triggering again. In this case, a recursive setTimeout would probably be better.

            – Kaiido
            Feb 5 '18 at 8:37













          • @Kaiido, My fault, but only tested async-await functionality

            – ryodeushii
            Feb 5 '18 at 8:40











          • "You should add async keyword to function definition in setInterval, because await can only work in async functions. " yet you did not use async in the actual code piece, making you answer not actually make sense. Please edit and clarify.

            – mibbit
            Jun 13 '18 at 23:29











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          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',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f48618023%2fhow-to-use-await-with-settimeout-and-setinterval%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          You can try to use it like this and it should work well



          var checkAuth = function(capabilities) {
          return new Promise(function(resolve) {
          setInterval(async function() {
          var session = await working.createSession(capabilities)
          if (session) {
          clearInterval(id);
          resolve(id);
          }
          }, 10);
          });
          }


          You should add async keyword to function definition in setInterval, because await can only work in async functions.
          Update: also move ,10 parameter from Promise definition to setInterval one






          share|improve this answer





















          • 1





            You should explain what you changed and why it is ok to make that change.

            – Felix Kling
            Feb 5 '18 at 8:26






          • 2





            Functions need to be async to be allowed to await things.

            – Jesper
            Feb 5 '18 at 8:28











          • your , 10 argument will be passed to the new Promise() constructor. And there should probably be a note about the fact that setInterval will not wait for its inner code to finish before triggering again. In this case, a recursive setTimeout would probably be better.

            – Kaiido
            Feb 5 '18 at 8:37













          • @Kaiido, My fault, but only tested async-await functionality

            – ryodeushii
            Feb 5 '18 at 8:40











          • "You should add async keyword to function definition in setInterval, because await can only work in async functions. " yet you did not use async in the actual code piece, making you answer not actually make sense. Please edit and clarify.

            – mibbit
            Jun 13 '18 at 23:29
















          1














          You can try to use it like this and it should work well



          var checkAuth = function(capabilities) {
          return new Promise(function(resolve) {
          setInterval(async function() {
          var session = await working.createSession(capabilities)
          if (session) {
          clearInterval(id);
          resolve(id);
          }
          }, 10);
          });
          }


          You should add async keyword to function definition in setInterval, because await can only work in async functions.
          Update: also move ,10 parameter from Promise definition to setInterval one






          share|improve this answer





















          • 1





            You should explain what you changed and why it is ok to make that change.

            – Felix Kling
            Feb 5 '18 at 8:26






          • 2





            Functions need to be async to be allowed to await things.

            – Jesper
            Feb 5 '18 at 8:28











          • your , 10 argument will be passed to the new Promise() constructor. And there should probably be a note about the fact that setInterval will not wait for its inner code to finish before triggering again. In this case, a recursive setTimeout would probably be better.

            – Kaiido
            Feb 5 '18 at 8:37













          • @Kaiido, My fault, but only tested async-await functionality

            – ryodeushii
            Feb 5 '18 at 8:40











          • "You should add async keyword to function definition in setInterval, because await can only work in async functions. " yet you did not use async in the actual code piece, making you answer not actually make sense. Please edit and clarify.

            – mibbit
            Jun 13 '18 at 23:29














          1












          1








          1







          You can try to use it like this and it should work well



          var checkAuth = function(capabilities) {
          return new Promise(function(resolve) {
          setInterval(async function() {
          var session = await working.createSession(capabilities)
          if (session) {
          clearInterval(id);
          resolve(id);
          }
          }, 10);
          });
          }


          You should add async keyword to function definition in setInterval, because await can only work in async functions.
          Update: also move ,10 parameter from Promise definition to setInterval one






          share|improve this answer















          You can try to use it like this and it should work well



          var checkAuth = function(capabilities) {
          return new Promise(function(resolve) {
          setInterval(async function() {
          var session = await working.createSession(capabilities)
          if (session) {
          clearInterval(id);
          resolve(id);
          }
          }, 10);
          });
          }


          You should add async keyword to function definition in setInterval, because await can only work in async functions.
          Update: also move ,10 parameter from Promise definition to setInterval one







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jan 2 at 11:59

























          answered Feb 5 '18 at 8:07









          ryodeushiiryodeushii

          796




          796








          • 1





            You should explain what you changed and why it is ok to make that change.

            – Felix Kling
            Feb 5 '18 at 8:26






          • 2





            Functions need to be async to be allowed to await things.

            – Jesper
            Feb 5 '18 at 8:28











          • your , 10 argument will be passed to the new Promise() constructor. And there should probably be a note about the fact that setInterval will not wait for its inner code to finish before triggering again. In this case, a recursive setTimeout would probably be better.

            – Kaiido
            Feb 5 '18 at 8:37













          • @Kaiido, My fault, but only tested async-await functionality

            – ryodeushii
            Feb 5 '18 at 8:40











          • "You should add async keyword to function definition in setInterval, because await can only work in async functions. " yet you did not use async in the actual code piece, making you answer not actually make sense. Please edit and clarify.

            – mibbit
            Jun 13 '18 at 23:29














          • 1





            You should explain what you changed and why it is ok to make that change.

            – Felix Kling
            Feb 5 '18 at 8:26






          • 2





            Functions need to be async to be allowed to await things.

            – Jesper
            Feb 5 '18 at 8:28











          • your , 10 argument will be passed to the new Promise() constructor. And there should probably be a note about the fact that setInterval will not wait for its inner code to finish before triggering again. In this case, a recursive setTimeout would probably be better.

            – Kaiido
            Feb 5 '18 at 8:37













          • @Kaiido, My fault, but only tested async-await functionality

            – ryodeushii
            Feb 5 '18 at 8:40











          • "You should add async keyword to function definition in setInterval, because await can only work in async functions. " yet you did not use async in the actual code piece, making you answer not actually make sense. Please edit and clarify.

            – mibbit
            Jun 13 '18 at 23:29








          1




          1





          You should explain what you changed and why it is ok to make that change.

          – Felix Kling
          Feb 5 '18 at 8:26





          You should explain what you changed and why it is ok to make that change.

          – Felix Kling
          Feb 5 '18 at 8:26




          2




          2





          Functions need to be async to be allowed to await things.

          – Jesper
          Feb 5 '18 at 8:28





          Functions need to be async to be allowed to await things.

          – Jesper
          Feb 5 '18 at 8:28













          your , 10 argument will be passed to the new Promise() constructor. And there should probably be a note about the fact that setInterval will not wait for its inner code to finish before triggering again. In this case, a recursive setTimeout would probably be better.

          – Kaiido
          Feb 5 '18 at 8:37







          your , 10 argument will be passed to the new Promise() constructor. And there should probably be a note about the fact that setInterval will not wait for its inner code to finish before triggering again. In this case, a recursive setTimeout would probably be better.

          – Kaiido
          Feb 5 '18 at 8:37















          @Kaiido, My fault, but only tested async-await functionality

          – ryodeushii
          Feb 5 '18 at 8:40





          @Kaiido, My fault, but only tested async-await functionality

          – ryodeushii
          Feb 5 '18 at 8:40













          "You should add async keyword to function definition in setInterval, because await can only work in async functions. " yet you did not use async in the actual code piece, making you answer not actually make sense. Please edit and clarify.

          – mibbit
          Jun 13 '18 at 23:29





          "You should add async keyword to function definition in setInterval, because await can only work in async functions. " yet you did not use async in the actual code piece, making you answer not actually make sense. Please edit and clarify.

          – mibbit
          Jun 13 '18 at 23:29




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f48618023%2fhow-to-use-await-with-settimeout-and-setinterval%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          MongoDB - Not Authorized To Execute Command

          How to fix TextFormField cause rebuild widget in Flutter

          in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith