[英]How to use await with setTimeout and setInterval?
I have a function createSession for getting users with returned session object. 我有一个函数createSession来获取返回会话对象的用户。 createSession either returns users or throws string exception.
createSession要么返回用户,要么抛出字符串异常。 My code is as follow, if session is successfull (which means I have users) continue code.
我的代码如下,如果session成功(这意味着我有用户)继续代码。
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.
因此,我希望修改我的代码,它会尝试让用户处于超时状态,以免每1秒尝试一次,直到达到超时30秒。
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. 我虽然在承诺中使用setTimout但问题是我不能在正常函数中使用await。 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. 您应该在
setInterval
中将async关键字添加到函数定义中,因为await
只能在async
函数中使用。 Update: also move ,10
parameter from Promise
definition to setInterval
one 更新:也将
,10
参数从Promise
定义移动到setInterval
一个
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.