简体   繁体   中英

How to use await with setTimeout and setInterval?

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);
    });
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM