感谢大家帮忙,没来得及看,用 2 楼的方法解决了
const axios = require('axios');
let dataQueue = [];
let isFetching = false;
async function fetchData() {
if (isFetching) return;
isFetching = true;
try {
const response = await axios.get('
https://example.com/api/data'); // 替换为实际的 API 地址
dataQueue = response.data.slice(0, 10); // 假设每次获取 10 条数据
} catch (error) {
console.error('Error fetching data:', error);
} finally {
isFetching = false;
}
}
async function getD() {
while (dataQueue.length === 0) {
if (!isFetching) {
await fetchData();
}
await new Promise(resolve => setTimeout(resolve, 100)); // 等待数据获取完成
}
return dataQueue.shift();
}
// 示例:同时执行 30 次 getD
(async () => {
const promises = Array.from({ length: 30 }, () => getD());
const results = await Promise.all(promises);
console.log(results);
})();