如何在JavaScript中设置函数执行顺序以使用回调函数?

时间:2016-01-01 13:49:57

标签: javascript node.js

我想处理函数执行顺序以使用回调。其实我正在学习Node.js.由于它的异步,我很难处理过程。无论如何,有3个函数有回调,

function first(callback){
    console.log("First");
    callback;
}

function second(callback){
    console.log("Second");
    callback;
}


function third(callback){
    console.log("Third");
}

// Let's run it!

first(second(third));

// result 

Second
First

我不明白结果的原因。我期待以下:

First
Second
Third

有什么问题?我怎么能正确地做到这一点?在Node.js中,人们通常使用回调来处理函数执行顺序吗?我觉得这有点复杂。不是吗?

4 个答案:

答案 0 :(得分:3)

我们假设你有2个函数,f和g

致电f(g())

时 首先评估

g(),以便为f()

提供正确的参数

所以如果你想首先执行f(),然后将结果作为参数传递给g,你必须反转流程。

g(f())

答案 1 :(得分:3)

正如其他答案中所解释的那样,

first(second(third));

这不符合你的想法。

我认为你真正打算做的是:

first(function(){
    second(function(){
        third(function(){
            // ...
        });
    });
});

在ES6(Node 4+)语法中,它将是:

first(() => second(() => third()));

但我更喜欢的是使用Promises的方法

function first(){
    return new Promise(function(resolve, reject){
        console.log("First");
        resolve();
    });
}

function second(){
    return new Promise(function(resolve, reject){
        console.log("Second");
        resolve();
    });
}

function third(){
    return new Promise(function(resolve, reject){
        console.log("Third");
        resolve();
    });
}

这完全消除了回调,并且更加了解实际的控制流程:

first()
.then(second)
.then(third);

checkout this article on promises 功能

使用ES7语法(babel / typescript),它变成了:

async function first(){
    console.log("First");
}
// async function second...
// async function third...

await first();
await second();
await third();

checkout this article on async/await 功能

答案 2 :(得分:2)

不要传递回调链接,而是执行second()的结果。您的代码可以写成:

var a = second(third);
first( a );

这应该更清楚,会发生什么:首先执行second()并将结果(undefined)作为"回调"到first()

此外,此代码中存在一些语法错误,可能应该如下所示:

function first(callback){
    console.log("First");
    callback();
}

function second(callback){
    console.log("Second");
    callback();
}

function third(callback){
    console.log("Third");
}

使用您的代码,回调永远不会被执行。

答案 3 :(得分:1)

正如kajyr所说,如果函数调用中的参数具有()(告诉函数执行),它将在实际调用其他函数之前执行。

要查看此行为,您可以使用'中的步骤逐步完成脚本。在你的JavaScript控制台中。 Treehouse did a decent post on using the js console.

<强> And here is a good explanation on stepping over, into, etc.

我稍微调整了你的代码,不确定这是否适合你,但这会给你正确的顺序。我只是先接受两个回调并按顺序调用它们。

此外,您需要在var名称后面的()来执行方法。 IE:callback();

function first(callback, cb){
    console.log("First");
    callback();
    cb();
}

function second(callback){
    console.log("Second");
}


function third(callback){
    console.log("Third");
}

// Let's run it!

first(second, third);

再一次,kajyr有一个正确的答案,我只是给出了另一个解决方案,并指出了你需要的方向它是如何工作的。