面试官:一万个任务按顺序执行怎么做。

123 阅读1分钟

看到标题,我们的第一想法肯定是then的链式调用,但是要一直写一万个then嘛,于是我们可以封装函数来大大简化代码。
有两种方式来实现封装:
1.递归,
2.循环 + await

递归

//1.递归
function promiseFn(arr, num = 0) {
    arr[num].then(() => {
        num++;
        if (num < arr.length) {
            console.log(`执行下一个!`);
            promiseFn(arr, num)
        }
    })
}

//测试
let a = new Promise((res, rej) => {
    setTimeout(() => {
        res(1)
        console.log(1);
    }, 1000);
})
let b = new Promise((res, rej) => {
    setTimeout(() => {
        res(2)
        console.log(2);
    }, 1000);
})
let c = new Promise((res, rej) => {
    setTimeout(() => {
        res(3)
        console.log(3);
    }, 1000);
})

let arr = [a, b, c]

promiseFn(arr)

image.png

循环 + await

//2.await
async function promiseFn() {
    for (let i = 0; i < arr.length; i++) {
        await arr[i].then(() => {
            console.log(`执行下一个!`);
        })
    }
}

//测试
let a = new Promise((res, rej) => {
    setTimeout(() => {
        res(1)
        console.log(1);
    }, 1000);
})
let b = new Promise((res, rej) => {
    setTimeout(() => {
        res(2)
        console.log(2);
    }, 1000);
})
let c = new Promise((res, rej) => {
    setTimeout(() => {
        res(3)
        console.log(3);
    }, 1000);
})

let arr = [a, b, c]

promiseFn(arr)

image.png


记录记录!