如何在React中等待带有分页的多个axios调用



React寻呼和多个Axios调用

我试图通过一个数字数组进行映射,并按顺序对每个数字进行api调用。然而,我调用的api有分页的结果,所以我不得不多次运行"函数2"并附加"下一个"光标。

我的问题是,在转移到循环中的下一个数组项之前,我无法让整个功能等待,直到没有更多分页的结果。

以下是我当前的代码:-

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();
}

它正在运行序列中的前两个数字,然后调用函数3.被难住了几个小时。。如有任何帮助,我们将不胜感激。感谢

如果您返回调用function2(一个promise(的结果,则返回的function2返回的promise将链接到它:

if(responseText._after){
return this.function2(number, after)
.then(others => [data, ...others]);
}
return [data];

最新更新