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?
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
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With