我正在用 Javascript 编写一个函数,该函数进行获取并接收分页的结果(正如预期的那样,结果很长)。
结果将包含一个“next_page”,它是下一页结果的获取主页 url。理想情况下,我想循环并不断获取,直到到达结果末尾,即“next_page”= null 时。
我似乎无法弄清楚如何在 next_page 不为空时循环遍历结果。似乎发生的事情是我陷入了无限的 while 循环。
欢迎任何建议。我在下面提供了伪代码。
while(next_page!=null){
fetch(apiUrl)
.then(res=>res.json())
.then(data => {
apiUrl=data["next_page]
}
if(apiUrl == null)
{
res.send(data)
break;
}
}
我在想 while 循环会让我迭代直到没有 next_page (也就是当它为空时)。看起来这只是无限循环而没有命中 fetch,因为 apiUrl 没有设置为 null。
最佳答案
您可以尝试下面的函数,而不是 while 循环
// Initial API Call
fetchData('http://localhost/test1.php?page=1');
// Create the function for API Call
function fetchData(apiUrl){
fetch(apiUrl)
.then(res=>res.json())
.then(data => {
console.log(data);
apiUrl = data['next_page'];
// Check next API url is empty or not, if not empty call the above function
if(apiUrl != '' && apiUrl != null){
fetchData(apiUrl);
}
})
}
关于javascript - 在 Javascript 中迭代分页 API 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58741697/