javascript - Console.log 作为 HTTP 请求发生在 Promise 数组中
问题描述
我正在向 API 发出一个 HTTP 请求,以获取数组上的尽可能多的条目。
我想要做的是 console.log 每次都在做一个请求,但我无法在它发生时记录它,它会等待所有的完成,然后它一次记录它。
const data = ['one','two']
// This simulates the API response I have no control here
const mockAPI = (timeout) => {
return new Promise((resolve, reject) => setTimeout(() => resolve(), timeout))
}
let counter = 0
// For each entry in the array
const promises = data.map(() => {
return new Promise(async (resolve, reject) => {
// Keep track of how many request are we up to
counter++
// Log it
console.log(counter)
// Make the call to the API
await mockAPI(3000)
// Do something with the data from API...
resolve()
})
})
// I collect the results of all promises to processes it later on
const result = Promise.all(promises)
我想要的是记录:
1
等待三秒钟 - 显然,只要 API 需要然后:
2
解决方案
对每个请求和 console.log尝试使用for loop
,await
当你使用 时Promise.All
,所有 fetches/async 任务并行运行(基于浏览器资源)
更新:增加了累积结果的方式
// This simulates the API response I have no control here
const mockAPI = (timeout) => {
const rand = Math.floor(Math.random() * 100);
return new Promise((resolve, reject) =>
setTimeout(() => resolve(rand), timeout)
);
};
(async function () {
const results = [];
let counter = 0;
for (let i = 0; i < 3; i++) {
console.log(counter++);
const res = await mockAPI(3000);
results.push(res);
}
console.log(results);
})();
推荐阅读
- salesforce - 在 SLDS 中,为什么闪电数据表的状态栏覆盖了日期编辑面板?
- linux - 在“menuconfig”中找不到“系统类型”
- fuzzing - BooFuzz UnicodeDecodeError
- python - 加速多线程下载
- python - Matplotlib 添加默认水印
- php - 在php中在图像上添加文本的字体路径问题
- typescript - 如何绑定 Material-Multi-Select 的值
- python - Django Login 将进行身份验证,但重定向仅在远程服务器上失败
- android - 例如,保存设置文件以更改背景主题的好方法是什么?
- javascript - 如何在javascript和javascript之间做ajax