Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set function execute order to using callback function in JavaScript?

I want to handle functions execute order to using callbacks. Actually I'm learning Node.js. Because of its async, It's difficult to me to handle process. Anyway, There are 3 function that has callback,

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

I don't understand why the result is. I expected below:

First
Second
Third

What's problem? How could I do it correctly? In Node.js, Do people usually handle functions excute order by using callbacks? that is little complex I think. Isn't it?

like image 312
ton1 Avatar asked Dec 25 '22 11:12

ton1


2 Answers

As explained in other answers,

first(second(third));

this doesn't do what you think it does.

I think what you actually meant to do was this:

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

In ES6 (Node 4+) syntax it'll be:

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

But what I prefer is an approach that uses 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();
    });
}

This gets rid of callbacks altogether, and makes more sense of the actual control flow:

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

checkout this article on promises

And with the ES7 syntax (babel/typescript) it simply becomes:

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

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

checkout this article on async/await

like image 124
laggingreflex Avatar answered Feb 15 '23 10:02

laggingreflex


Let's say you have 2 functions, f and g

When you call f(g())

g() is evaluated first in order to provide the correct arguments for f()

so if you want to have f() executed first, and then the result passed to g as a parameter, you have to inverse the flow.

g(f())

like image 32
Carlo Avatar answered Feb 15 '23 11:02

Carlo