admin管理员组文章数量:1355703
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;
}
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.
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?
In case it makes a difference, I'm using Angular 4.
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;
}
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.
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?
In case it makes a difference, I'm using Angular 4.
Share Improve this question edited Aug 22, 2017 at 9:43 Estus Flask 224k79 gold badges472 silver badges611 bronze badges asked Aug 22, 2017 at 9:31 Stephan MullerStephan Muller 27.6k18 gold badges86 silver badges127 bronze badges2 Answers
Reset to default 7This 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;
}
You can implement this with async/await
without recursion:
let fetch = async () {
try {
let start = 0;
let all = [];
let newData;
do {
newData = await getData(start, 1000);
start += newData.length;
all = all.concat(newData);
} while (newData.length > 0);
return all;
} catch (err) {
console.log(err);
}
}
本文标签:
版权声明:本文标题:javascript - Recursively calling an asynchronous API call - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743961345a2569086.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论