[英]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.