问题描述
我正在尝试从API中获取数据,该API每次调用仅返回1000个项目,我想递归地执行此操作,直到获得所有数据为止.
I'm trying to fetch data from an API that only returns 1000 items per call, and I want to do this recursively until I have all the data.
我事先不知道总共有多少个项目,所以每次通话后我都必须检查
I don't know beforehand how many items there are in total, so after every call I have to check
如果通话是同步的,我会使用类似以下的内容:
If the call was synchronous, I'd use something like this:
function fetch(all, start) {
const newData = getData(start, 1000);
all = all.concat(newData);
return (newData.length === 1000) ? fetch(all, all.length) : all;
}
但是,这里的getData()
调用是异步的.使用Promise.all()
无效,因为我事先不知道需要多少个电话,所以我无法准备一系列电话.
However, the getData()
call here is asynchronous. Using a Promise.all()
doesn't work because I don't know beforehand how many calls I need so I can't prepare an array of calls.
我有种可以使用生成器或async
/await
解决此问题的感觉,但我不知道如何解决.谁能指出我正确的方向?
I have the feeling I could solve this with generators or with async
/await
but I don't know how. Can anyone point me in the right direction?
以防万一,我使用的是Angular 4.
In case it makes a difference, I'm using Angular 4.
推荐答案
这取决于您的情况.考虑到getData
返回一个诺言,它是:
This depends on how things are done in your case. Considering that getData
returns a promise, it is:
async function fetch(all, start) {
const newData = await getData(start, 1000);
all = all.concat(newData);
return (newData.length === 1000) ? await fetch(all, all.length) : all;
}
这篇关于递归调用异步API调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!