function fetchBox(param) {
return new Promise((resolve, reject) => {
setTimeout(() => {
let box = {}
box[param] = [1, 2, 3]
resolve(box)
}, 5000);
})
}
let params = ['apple', 'banana', 'orange']
let result = []
// 1.不应该每个请求都依次 await
params.forEach(async (param) => {
result.push(await fetchBox(param))
})
// 2.而是将同类的请求放到Promise.all()中去
let pool = params.map(param => {
return fetchBox(param)
})
let promiseResult = Promise.all(pool)
console.log(result)
console.log(promiseResult)
使用Promise.all()优化请求
最新推荐文章于 2024-09-18 11:51:54 发布