Promise All应该是request或Promise的数组,在map()中应该返回request。试试这个
问题:case1的输出是从0到4,这是正常的,而案例2的输出是随机的。
我知道case1的结果之所以有序,是因为请求是在上一个请求的结果到来之后发送的。在情况2中,请求不会等待先前请求的结果。
我的问题是,是否也有办法保持案例2的结果?
案例1
const main = async () => {
const arr = Array.of(...[1,2,3,4,5])
for (let i=0;i<arr.length;i++) {
console.log(`request:${i}`)
const res = await request(i)
console.log(res)
}
console.log("next step")
}
const request = (i:number):Promise<number> => {
return new Promise<number>(((resolve, reject) => {
setTimeout(()=>{
resolve(i)
},Math.random() * 1000)
}))
}
输出1
closure
request:0
0
request:1
1
request:2
2
request:3
3
request:4
4
next step
案例2
const main = async () => {
const arr = Array.of(...[1,2,3,4,5])
await Promise.all(arr.map(async (v,i) => {
console.log(`request:${v}`)
const res = await request(v)
console.log(`result:${res}`)
console.log(res)
})).catch((e) => {
})
console.log("next step")
}
const request = (i:number):Promise<number> => {
return new Promise<number>(((resolve, reject) => {
setTimeout(()=>{
resolve(i)
},Math.random() * 1000)
}))
}
main()
输出2
request:1
request:2
request:3
request:4
request:5
result:4
4
result:5
5
result:1
1
result:3
3
result:2
2
next step
Promise.all()
按相同顺序返回一个结果数组;他们就是解决不了问题。您可以在request
承诺内返回响应,然后。。。
const [result1, result2, result3] = await Promise.all([promise1, promise2, promise3]);
或者,如果你想迭代一个数组。。。
const results = await Promise.all([promise1, promise2, promise3]);
const main = () => {
const arr = Array.of(...[1,2,3,4,5])
Promise.all(arr.map((v,i) => {
console.log(`request:${v}`)
return request(v)
})).then((res)=>{
res.forEach((val)=>{
console.log(`result:${val}`)
})
}).catch((e) => {
})
console.log("next step")
}
const request = (i)=> {
return new Promise((resolve, reject) => {
setTimeout(()=>{
resolve(i)
}, Math.floor(Math.random() * 10)*1000)
})
}
main()