js 数组 异步的坑 map ,forEach ,some,every

forEach

数组里面 forEach 如果带 await 的话,里面 是并行的

    [1,2,3].forEach(async (x) => {
      await xxx(x)
    })

这里面 1 2 3 是 会同时被 xxx 函数处理的

想要并行的话,得写成这样

    for (const x of [1, 2, 3]) {
      await xxx(x)
    }

这样 1 ,2 ,3 是 顺序处理的

map

map 里面 有 await 的话

返回 的是 个 Promise 数组 ,需要得到结果 ,得加 await Promise.all

如下图

some ,every

这个 不能用自带的 ,自带的有坑

如下图

这里 sizeMoreThan512 bool 始终是 true , 所以不能用自带的

需要自己定义一个函数 来弄

const arr = [1, 2, 3];

const asyncSome = async (arr, predicate) => {
	for (let e of arr) {
		if (await predicate(e)) return true;
	}
	return false;
};
const res = await asyncSome(arr, async (i) => {
	console.log(`Checking ${i}`);
	await sleep(10);
	return i % 2 === 0;
});

// Checking 1
// Checking 2

console.log(res);
// true

every 同理


const arr = [1, 2, 3];

const asyncEvery = async (arr, predicate) => {
	for (let e of arr) {
		if (!await predicate(e)) return false;
	}
	return true;
};
const res = await asyncEvery(arr, async (i) => {
	console.log(`Checking ${i}`);
	await sleep(10);
	return i < 2;
});

// Checking 1
// Checking 2

console.log(res);
// false

参考来源 https://advancedweb.hu/how-to-use-async-functions-with-array-some-and-every-in-javascript

posted @ 2022-10-08 09:16  ifnk  阅读(693)  评论(0编辑  收藏  举报