MST

星途 面试题库

面试题:JavaScript 闭包与回调函数结合实现异步操作

使用闭包与回调函数,编写一段 JavaScript 代码实现依次异步执行三个函数,每个函数执行完后打印当前函数名,并且最后打印 'All functions completed'。
13.1万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试
function first(cb) {
    setTimeout(() => {
        console.log('first');
        cb();
    }, 1000);
}

function second(cb) {
    setTimeout(() => {
        console.log('second');
        cb();
    }, 1000);
}

function third(cb) {
    setTimeout(() => {
        console.log('third');
        cb();
    }, 1000);
}

function executeFunctions() {
    const innerFunction = (index, functions) => {
        if (index >= functions.length) {
            console.log('All functions completed');
            return;
        }
        functions[index](() => innerFunction(index + 1, functions));
    };
    innerFunction(0, [first, second, third]);
}

executeFunctions();