带有map的并行请求和带有promise.all的for循环,然后

问题描述 投票:0回答:1

我正在尝试向第三方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 
  })
}

request函数调用API,然后将结果附加到一个csv文件中,我想做的是在最后一个诺言已附加到文件中之后,我想读取该文件并处理其数据,位于这一点我遇到了问题,我的csv格式错误。

我不确定是否应该使用fs进行同步或异步,但是想知道并行请求上的这种方法是否有问题。

任何帮助,不胜感激。

javascript node.js promise es6-promise fs
1个回答
0
投票

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

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