我有如下的脚本。
它启动多个API访问。
var temp = [];
for (let i = 0; i < `10;i++){
var url = `http://www.myapi.com/api/?id=${i}`;
axios.get(url).then(res =>{
temp[i] = res['data'];
//I want to do something if every API get the results.
}).catch(res => {
console.log("axios error");
});
}
现在我想等待每 10 个 api 访问完成。
这可能吗?我该怎么做?
您可以使用 Promise.all 来等待多个请求,
Promise.all([
fetch('https://jsonplaceholder.typicode.com/posts'),
fetch('https://jsonplaceholder.typicode.com/users')
]).then(function (responses) {
// Get a JSON object from each of the responses
return Promise.all(responses.map(function (response) {
return response.json();
}));
}).then(function (data) {
// Log the data to the console
// You would do something with both sets of data here
console.log(data);
}).catch(function (error) {
// if there's an error, log it
console.log(error);
});