使用 map 和 for 循环的并行请求 promise.all 然后

Parallel requests with map and for loop with promise.all and then

我正在尝试 运行 向第三方 API 并行请求数百个关键字,每个关键字有五种不同类型的请求,它正在工作,但在承诺解决后我必须操纵数据更远,有时更早。


const myFunc = async () => {

  const keywords = ['many', 'different', 'type', 'of', 'keywords']

  // Create promise's array      
  let promises = keywords.map((keyword, index) =>
    new Promise(resolve => setTimeout(() => {
      for (let page = 1; page <= 5; page++) 
        resolve(request(keyword, page))
      }, index * 100)
   ))

  // Resolve
  await Promise.all(promises).then(() => { 
    // Here is where I hope to be dealing with the fully resolved data to read and write the file 
  })
}

请求函数调用 API 然后将结果附加到 csv 文件,我想做的是当最后一个承诺附加到文件时,我想读取该文件并操纵了它的数据,此时我遇到了问题,因为 csv 格式不正确。

我可以归结为我使用 fs 的方式,我不确定它应该是同步的还是异步的,但想知道这种方法在并行请求上是否有问题。

非常感谢任何帮助。

您需要 两个 Promise.alls - 一个在 new Promise 的循环内,一个在外部等待所有请求完成:

const delay = ms =>  new Promise(resolve => setTimeout(resolve, ms));
const pageCount = 5;
const myFunc = async () => {
  const keywords = ['many', 'different', 'type', 'of', 'keywords']
  const promises = keywords.map((keyword, index) =>
    delay(index * 100 * pageCount).then(() => Promise.all(Array.from(
      { length: pageCount },
      (_, i) => delay(100 * (i + 1)).then(() => request(keyword, i + 1))
    )))
  );
  await Promise.all(promises).then(() => { 
    // Here is where I hope to be dealing with the fully resolved data to read and write the file 
  })
}

由于每次调用之前都需要有另一个延迟,因此使用 for..of 循环可能更容易:

const delay = ms =>  new Promise(resolve => setTimeout(resolve, ms));
const pageCount = 5;
const myFunc = async () => {
  const keywords = ['many', 'different', 'type', 'of', 'keywords']
  for (const keyword of keywords) {
    for (let page = 1; page <= 5; page++) {
      await delay(100);
      await request(keyword, page);
    }
  }
  // Here is where I hope to be dealing with the fully resolved data to read and write the file
};