Axios 循环承诺
Axios promise in a loop
在 React 中,我想将函数 getRepos()
传递给 componentDidMount()
。 getRepos()
等待另一个传递来自 API 调用的数据的函数。我希望能够将所有承诺放在一个数组中,然后解决它。我怎么做?到目前为止,这是我得到的:
async getRepos() {
const tmpRepos = [];
const numPages = await this.getOrgPages();
for (let page = 1; page <= numPages; page += 1) {
axios.get(`https://api.github.com/orgs/angular/repos?page=${page}&per_page=100&${API_KEY}`)
}
axios.all(tmpRepos).then(res => console.log(res));
}
但只记录一个空数组
创建一个新数组,并用axios.get
调用的结果填充它,在axios.all
中使用这个数组:
async getRepos() {
const ops = [];
const numPages = await this.getOrgPages();
for (let page = 1; page <= numPages; page += 1) {
let op = axios.get(`https://api.github.com/orgs/angular/repos?page=${page}&per_page=100&${API_KEY}`);
ops.push(op);
}
let res = await axios.all(ops);
console.log(res);
}
在 React 中,我想将函数 getRepos()
传递给 componentDidMount()
。 getRepos()
等待另一个传递来自 API 调用的数据的函数。我希望能够将所有承诺放在一个数组中,然后解决它。我怎么做?到目前为止,这是我得到的:
async getRepos() {
const tmpRepos = [];
const numPages = await this.getOrgPages();
for (let page = 1; page <= numPages; page += 1) {
axios.get(`https://api.github.com/orgs/angular/repos?page=${page}&per_page=100&${API_KEY}`)
}
axios.all(tmpRepos).then(res => console.log(res));
}
但只记录一个空数组
创建一个新数组,并用axios.get
调用的结果填充它,在axios.all
中使用这个数组:
async getRepos() {
const ops = [];
const numPages = await this.getOrgPages();
for (let page = 1; page <= numPages; page += 1) {
let op = axios.get(`https://api.github.com/orgs/angular/repos?page=${page}&per_page=100&${API_KEY}`);
ops.push(op);
}
let res = await axios.all(ops);
console.log(res);
}