0

I'm new to ES6 and Node.js

I would like to understand how callback functions work in a synchronous environment and asynchronous environment.

I tried to run the following in Node:

function func1() { 
    console.log('hello'); 
}

func1(function(){ 
    console.log('world');
}); 

From my understanding of asynchronous callbacks, func1 should execute first, and when func1 finishes execution it calls back the function inside its argument list.

So in this case:

console.log('world') 

should execute in second place, but i'm only getting as an output:hello.

Am i missing something? Can someone explain to me with clear examples how callbacks work? Is it the same in a synchronous environment?

2 Answers2

2

You should start by examining your func1() function:

function func1() { 
    console.log('hello'); 
}

The most important thing to recognize is that it takes zero arguments. The result is that it doesn't matter what you pass to it. For example:

func1("world")
func1(1)
func1(false)
func1(function (){console.log('world)}

all do exactly the same thing because func1() ignores everything passed in as an argument.

Functions that don't ignore their parameters are what you need if you want to pass a callback, because they need to do something with that callback. So a function taking a callback should have a signature more like this:

function func1(some_argument){
   // do something with argument
}

If you're expecting that argument to be a function, the natural things to do would be to execute it like:

function func1(some_function){
    // call that function
    some_function()
}

So for your example, you would end up with:

function func1(callback) { 
    console.log('hello');
    callback() 
}

func1(function(){ 
    console.log('world');
}); 

which would result in two console.log()s.

Also, since it was in the title, there isn't anything asynchronous going on here.

Mark
  • 90,562
  • 7
  • 108
  • 148
1

So when you run func1(function(){...}) you're actually passing the unnamed or 'anonymous' function as an argument to func1. To function as a callback however, you need to explicitly execute it.

function func1(fn) { 
    console.log('hello'); 
    fn();
}

func1(function(){ 
    console.log('world');
}); 

In other node libraries, the developers are most likely handling the callbacks you give to their functions, which is why they work.

Hope this helps!