关于for循环和forEach的异步同步化

Last updated on July 9, 2025 pm

前言

首先,在操作大量数据时,forEach比for循环消耗更大一些

异步同步化的支持度

forEach

1
2
3
4
5
6
7
8
9
10
let arrs = Array.from({length:3},(_,index)=>index+1);
let datas=[];
arrs.forEach(async item=>{
const {data} = await uni.request({
url:"http://jsonplaceholder.typicode.com/posts/"+item
})
datas.push(data)
})
console.log(datas);
// 输出[]"空数组"

在上面代码中uni.request返回promise对象,使用async/await是可以实现异步等待的,按照预想应该是forEach后面打印datas是一个数组对象,包含三次接口返回的数组,但是最后打印结果是空数组,说明在forEach函数内,不支持await异步等待。

for循环

可以将上面forEach代码改造成for循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
async function fetchData() {
let arrs = Array.from({length:3},(_,index)=>index+1);
//生成数组[1,2,3]
let datas=[];
for (let i = 0; i < arrs.length; i++) {
const {data} = await uni.request({
url:"http://jsonplaceholder.typicode.com/posts/"+arrs[i]
});
datas.push(data);
}
console.log(datas);
}
fetchData();
// [{...},{...},{...}]

改造成for循环之后,是可以按照预期拿到数组集合的,但是这种查询效率会非常低,我们这里是为了证明for循环是可以做异步等待的,要是真实的场景,建议看下面map+Promise.all的实现方法。

map+Promise.all

将异步请求map到新数组中,使用Promise.all同事处理多个Promise
下面这个代码块,是解决for循环异步同步化性能消耗过大的问题

1
2
3
4
5
6
7
8
9
10
let arrs = Array.from({length:3},(_,index)=>index+1);
const promises = arrs.map(async (num) => {
const result = await uni.request({
url:"http://jsonplaceholder.typicode.com/posts/"+num
})
return result;
});
Promise.all(promises).then(res=>{
console.log(res);
})

下面是Promise.all请求,network请求的状况,会同时发送请求,会节省很多的时间

下面是for循环异步同步化出现的网络请求状态,会等待一个完成之后再请求另一个,所以时间上会更慢一些


关于for循环和forEach的异步同步化
https://angelaggression.github.io/2025/07/09/关于for循环和foerEach的异步操作/
Author
BurnedWings
Posted on
July 9, 2025
Licensed under