我试图通过使用while循环查看每个HTTP请求之间的响应,但这导致我的浏览器异常反应,迫使我退出它。有人可以给我一些指示吗?我正在尝试发送“唤醒”命令,如果它处于睡眠状态,我会收到408错误,如果它处于唤醒状态,我会得到200 OK。我在想,也许我应该在每个http请求之间添加10秒钟的睡眠功能,但我认为没有像Python中那样简单的“睡眠”功能。
state = "asleep"
while (state === "asleep") {
this.wakeUp(user).then(function (response) {
if (response.status === 200):
state = "awake";
});
}
wakeUpVehicle(user) {
return new Promise(function(resolve) {
fetch(url + "/wake_up", {
method: "post",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + access_token
}
})
.then(res => res.json())
.then(json => {resolve(json["response"])})
});
}
我将不胜感激! :-)谢谢
答案 0 :(得分:6)
没有简单的“睡眠”,但是您可以轻松地自己写:
const timer = ms => new Promise(res => setTimeout(res, ms));
然后就这么简单:
let state = "asleep"; // always declare variables!
(async function polling() { // leave the synchronous track
while(true) { // async infinite loops are not as bad as they might seem
const response = await wakeUp(user);
state = response.status ? "awake" : "asleep"; // not sure if this is what you wanted, edit according to your needs
await timer(10 * 1000); // wait for 10secs before checking again
}
})();