[英]How do you await multiple axios calls with pagination in React?
反应分页和多个 Axios 调用
我正在尝试通过一组数字 map 并按顺序对每个数字进行 api 调用。 但是,我正在调用的 api 具有分页结果,因此我必须多次运行“函数 2”并附加“下一个”cursor。
我的问题是,在移动到循环中的下一个数组项之前,我无法让整个功能等到没有更多的分页结果。
以下是我目前的代码:-
function1() {
let arr = ['837493000', '837493001'];
Promise.all(arr.map((num) => this.function2(num))).then(() => {
this.function3();
});
}
function2(number, after) {
let api = `https://test-api.local/${number}?client_id=123456789`;
if(after){
api = `https://test-api.local/${number}?client_id=123456789&cursor=${after}`;
}
const result = axios.get(api, {
method: 'get',
headers: {
'Client-ID': '123456789'
}
})
.then((response) => response.data)
.then((responseText) => {
if(responseText){
let data = responseText.comments;
if(responseText._after){
this.function2(number, responseText._after);
}
return data;
}
});
}
function3() {
console.log('I ran');
}
componentDidMount(){
this.function1();
}
它正在运行序列中的前 2 个数字,然后调用 function 3.. 被难住了几个小时.. 任何帮助将不胜感激。 谢谢
如果您从调用function2
(承诺)返回结果,则返回的function2
返回的 promise 将链接到它:
if(responseText._after){
return this.function2(number, after)
.then(others => [data, ...others]);
}
return [data];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.