为什么没有执行数组函数的回调?

问题描述 投票:0回答:1

我是nodejs的新手。我创建了一个函数数组,我不能让我的函数回调执行。有谁能够帮我?

'using strict'

const tasks = [];
tasks.push(function (callback)  {
    console.log('Hi.. executing task 1'); 
    return callback;
});
tasks.push(function (callback) { 
    console.log('Hi.. executing task 2'); 
    return callback; 
});
tasks.push(function (callback) { 
    console.log('Hi.. executing task 3'); 
    return callback; 
});

function iterate(index, callback) {
    if (index === tasks.length) {
        return callback();
    }
    const task = tasks[index];
    task(function () {
        console.log('Hi.. executing task callback'); 
        //the line, I really want to include in here is
        //   iterate(index + 1, callback);
     });
    iterate(index + 1, callback);
}
function finish() {
    console.log('Execution complete');
}
iterate(0, finish);

控制台显示

嗨..执行任务1

嗨..执行任务2

嗨..执行任务3

执行完成

node.js
1个回答
0
投票

如果你仔细观察它,你就不会执行回调,而只是返回它。所以你也可以

    cbFunc = task(function () {
        console.log('Hi.. executing task callback'); 
        //the line, I really want to include in here is
        //   iterate(index + 1, callback);
     });
    cbFunc();

要么

tasks.push(function (callback)  {
    console.log('Hi.. executing task 1'); 
    return callback();
});
© www.soinside.com 2019 - 2024. All rights reserved.