[英]setInterval loop doesn't wait at await
I made an example function 'webrequest()', imagine that this is a webrequest that takes 2 to get a response. 我制作了一个示例函数'webrequest()',假设这是一个需要2响应的webrequest。 I want to send a new webrequest after each response I receive.
我想在收到每个回复后发送一个新的webrequest。 When I run te loop it just doesn't wait at the await and it sends another webrequest.
当我运行te loop时,它只是不等待,而是发送另一个webrequest。
I have no idea what I did wrong. 我不知道我做错了什么。 I can't find posts about this problem(maybe i'm searching wrong).
我找不到有关此问题的帖子(也许我搜索错了)。
function webrequest() {
return new Promise((resolve) => {
setTimeout(()=>{
resolve()
},2000)
})
}
function loopTest() {
setInterval(async () => {
console.log('Welcome')
await webrequest();
console.log('Bye')
},10)
}
loopTest()
So the output should be. 所以输出应该是。
Welcome
(2 seconds timeout)
Bye
Welcome
(2 seconds timeout)
Bye
...
There is no sense in using a short running setInterval
then. 然后使用短时间运行
setInterval
是没有意义的。 Just use a loop: 只需使用一个循环:
(async function() {
while(true) {
console.log('Welcome')
await webrequest();
console.log('Bye')
}
})();
As mentioned above setInterval does not play well with promises if you do not stop it. 如上所述,如果您不停止setInterval,它将不能很好地履行诺言。 In case you clear the interval you can use it like:
如果您清除间隔,可以像这样使用它:
It seems that it's setTimeout that fits the case. 似乎适合情况的setTimeout。 It should be isside promise in order to be used with async..await:
为了与async..await一起使用,它应该是side promise。
function first(){ console.log('Welcome') } function second(){ console.log('Bye') } async function loopTest(){ await new Promise(resolve => setTimeout(() => resolve(first()), 1000)); await new Promise(resolve => setTimeout(() => resolve(second()), 1000)); } loopTest()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.