n3s*_*tle 2 javascript promise async-await reactjs axios
在 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));
}Run Code Online (Sandbox Code Playgroud)
但只记录一个空数组
创建一个新数组,并通过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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4232 次 |
| 最近记录: |