[英]Javascript - How can I wait 10 seconds for a promise to return?
我試圖通過使用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"])})
});
}
我將不勝感激任何幫助! :-) 謝謝
沒有簡單的“睡眠”,但是您可以輕松地自己寫:
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
}
})();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.