微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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 loopawait 当您使用 Promise.All 时,所有提取/异步任务都会并行运行(基于浏览器资源)

更新:增加了累积结果的方式

// 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);
})();

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。