[英]async Do While loop
I need to pull data from an API, but it sends me the data in pages of 100 + the total count of results.我需要从 API 中提取数据,但它以 100 页 + 结果总数的形式向我发送数据。 The way I tried doing is我尝试做的方式是
let count, page = 0;
do {
++page
pullData(page, () => {
count = data.count
});
} while (page < count / 100);
but the code checks the condition of the loop before count is initialized (page < undefined / 100), and the loop ends up running only the first time.但是代码在 count 初始化之前检查循环的条件(page < undefined / 100),并且循环只在第一次运行时结束。
Is there a way to make the loop wait for the async body to run before checking the condition?有没有办法让循环在检查条件之前等待异步主体运行?
Use async/await
or recursive functions like this:使用async/await
或递归函数,如下所示:
const recursive = (page) => {
pullData(page, () => {
count = data.count;
if (page < count / 100) {
recursive(++page)
}
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.