Promise解決并發(fā)請求和async/await解決并發(fā)請求
有的時候會出現(xiàn)一種情況,就是你需要調(diào)用多次API,因為可能調(diào)一次返回的數(shù)據(jù)量過大,占滿了帶寬就直接卡死,但是你又不想每次只調(diào)用一個,想每次調(diào)用多個,你就可以嘗試下面的方法:
使用Promise解決并發(fā)問題
function async concurrentRequests(args, len = 10) {
const recordArr = 0 // 用來記錄當(dāng)前有多少個請求
for(let i = 0; i < args.length; i++) {
const rsp = request(i) // 假設(shè)這就是我們的請求
recordArr++ // 請求數(shù)加一
rsp?.then((res, rej) => {
if(res?.Status === 'success') { // 假設(shè)我們以請求結(jié)果的Status判斷成功與否
// 進(jìn)行正常的業(yè)務(wù)交流
}
recordArr--
})
if(recordArr.length === len) { // 到達(dá)極限了
await Promise.race(recordArr) // 等待recordArr的變化
}
}
}
使用async/await控制并發(fā)請求
async function concurrentRequests(urls, limit = 5) {
const queue = urls.map(url => fetch(url)) // 將請求放到一個數(shù)組隊列中
return new Promise((resolve, reject) => {
const results = [] // 記錄結(jié)果數(shù)組
let count = 0 // 記錄當(dāng)前請求量
const next = async () => {
if(queue.length > 0) {
while(queue.length > 0 && count < limit) {
count++
const req = queue.shift() // 取出請求
req().then(res => {
results.push(result)
}).catch(err => {
console.error(err)
}).finally(() => {
count-- // 放出
next()
})
}
} else if(count === 0) {
resolve(results)
}
}
next()
})
}
行百里者半九十
浙公網(wǎng)安備 33010602011771號