MST

星途 面试题库

面试题:JavaScript 中如何利用回调函数实现简单的异步任务队列

假设有一系列异步任务,每个任务以回调函数的形式定义。请编写代码实现一个任务队列,使得这些任务按顺序依次执行,并且在所有任务完成后执行一个最终的回调函数。例如任务数组 `tasks = [task1, task2, task3]`,每个任务函数如 `function task1(callback) { setTimeout(() => { console.log('Task 1 completed'); callback(); }, 1000); }`,要求实现任务按顺序执行并在全部完成后执行最终回调。
18.3万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试
function task1(callback) {
    setTimeout(() => {
        console.log('Task 1 completed');
        callback();
    }, 1000);
}

function task2(callback) {
    setTimeout(() => {
        console.log('Task 2 completed');
        callback();
    }, 1000);
}

function task3(callback) {
    setTimeout(() => {
        console.log('Task 3 completed');
        callback();
    }, 1000);
}

function executeTasks(tasks, finalCallback) {
    function runTask(index) {
        if (index >= tasks.length) {
            finalCallback();
            return;
        }
        tasks[index](() => {
            runTask(index + 1);
        });
    }
    runTask(0);
}

const tasks = [task1, task2, task3];
executeTasks(tasks, () => {
    console.log('All tasks completed');
});