我正在嘗試創建一個回圈來獲取API中的一些資訊,首先我需要這個回圈來等待請求完成并在繼續下一個陣列值之后,在回圈完成后,我需要它來呼叫該函式每 5 秒再次,但僅在前一個呼叫結束后。
像這樣的東西:
let ids = [1, 2];
async function getInfoAPI(ids) {
for (const id of ids){
const apiInfo = await fetch(`https://apiurl/${id}`);
const infoJSON = await apiInfo.json();
//Do more things here
}
}
現在我需要呼叫該函式并等待回圈完成。回圈完成后等待 5 秒,然后再次呼叫 getInfoFromAPI 函式。我嘗試了 setInterval 但如果回圈由于某種原因需要超過 5 秒的回應時間,即使它沒有完成前一個回圈,也會再次呼叫 getInfoFromAPI。
setInterval(function(){
getInfoAPI(ids);
}, 5000);
有什么辦法可以使用承諾或類似的東西來做到這一點?
謝謝
uj5u.com熱心網友回復:
使用遞回:
async function getInfoPeriodically() {
await getInfoAPI(ids);
setTimeout(() => {
getInfoPeriodically()
}, 5000);
}
您可以添加引數來自定義此函式/傳入值,但這就是想法。
uj5u.com熱心網友回復:
您可以通過匯入setTimeout
NodeJs 16 附帶的基于 Promise 并按如下方式使用它來實作此目的:
進口:
import { setTimeout } from "timers/promises"
利用:
while (true) {
await getInfoAPI(ids);
await setTimeout(5000);
}
uj5u.com熱心網友回復:
你可以這樣做:
function run() {
getInfo(...).then(() => {
setTimeout(run, 5000)
});
}
run().catch(err => {
console.log(err);
});
或者,我更喜歡使用setTimeout()
. 我是最新版本的 nodejs,你可以使用timersPromises.setTimeout()
它并回傳一個承諾:
import { setTimeout } from 'timers/promises';
async function run() {
await getInfo(...)
await setTimeout(5000);
return run();
}
run().catch(err => {
console.log(err);
});
或者,使用while
回圈:
import { setTimeout } from 'timers/promises';
async function run() {
while (true) {
await getInfo(...)
await setTimeout(5000);
}
}
run().catch(err => {
console.log(err);
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/486174.html
標籤:javascript 节点.js api 异步等待 拿来
下一篇:需要在php中轉換一個值輸出