Reputation: 143
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);
});
}
Upvotes: 4
Views: 5541
Reputation: 121
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
Upvotes: 3