Console.log 因为 HTTP 请求在 promise 数组中发生

Console.log as HTTP requests are happening in promise array

我正在向 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

为每个请求尝试 for loopawait 和 console.log 当您使用 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);
})();