forEach解决异步问题

249 阅读1分钟

假如:

const arr = [1, 2, 3, 4];
async function fn() {
    arr.forEach(async (item, index) => {
        console.log(111, "开始");
	await Waiting(1000);
	console.log(222222, "等待1s");
	let code = await Waiting(2000);
	console.log(222222, "等待2s");
	if (code == 3) {
            await Waiting(5000);
            console.log(222222, "分支等待5s");
	}
	await Waiting(3000);
	console.log(333333, "结束");
    });
}
function Waiting(ms) {
    return new Promise((resolve, reject) => {
	setTimeout(() => {
		resolve(ms == 2000 ? 3 : 0);
	}, ms);
    });
}
fn();

执行的结果:

image.png 在forEach里面执行的回调他们之间的关系是异步,不是异步

可以使用for循环

const arr = [1, 2, 3, 4];
async function fn() {
    for (let i = 0; i < arr.length; i++) {
        console.log(111, "开始");
        await Waiting(1000);
        console.log(222222, "等待1s");
        let code = await Waiting(2000);
        console.log(222222, "等待2s");
        if (code == 3) {
            await Waiting(5000);
            console.log(222222, "分支等待5s");
        }
        await Waiting(3000);
	console.log(333333, "结束");
    }
}
function Waiting(ms) {
    return new Promise((resolve, reject) => {
	setTimeout(() => {
		resolve(ms == 2000 ? 3 : 0);
	}, ms);
    });
}
fn();

可以使用for of

const arr = [1, 2, 3, 4];
async function fn() {
    for (let i of arr) {
        console.log(111, "开始");
        await Waiting(1000);
        console.log(222222, "等待1s");
        let code = await Waiting(2000);
        console.log(222222, "等待2s");
        if (code == 3) {
            await Waiting(5000);
            console.log(222222, "分支等待5s");
        }
        await Waiting(3000);
	console.log(333333, "结束");
    }
}
function Waiting(ms) {
    return new Promise((resolve, reject) => {
	setTimeout(() => {
		resolve(ms == 2000 ? 3 : 0);
	}, ms);
    });
}
fn();

或者可以重写forEach方法

Array.prototype.myForEach = async function (cd) {
	let _arr = this;
	let _leg = _arr.length;
	let _arrTow = arguments[1] || window;
	if (!Array.isArray(_arr)) {
		throw new TypeError("The caller of myfoeach must be the type 'Array'");
	}
	for (let i = 0; i < _leg; i++) {
		await cd.call(_arrTow, _arr[i], i, _arr);
	}
};

还可以用reduce,生成器迭代器........