[英]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.all
s - 一个在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
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.