我正在尝试对数百个关键字向第三方 API 运行并行请求,每个关键字有五种不同类型的请求,它正在工作,但在 promise 解决后,我必须进一步操作数据,有时它会提前一点.
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文件中,我想做的是当最后一个 promise 被附加到文件中时,我想读取该文件并操作其数据,是此时我遇到了 csv 格式错误的问题。
我可以确定我使用 fs
的方式,但不确定它是同步还是异步,但想知道这种方法在并行请求上是否有问题。
任何帮助将不胜感激,非常感谢。
最佳答案
您需要两个 Promise.all
- 一个在 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
};
关于javascript - 使用map 进行并行请求,使用promise.all 进行for 循环,然后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59373811/