'Callback function confusion

function print(){
  console.log("hello");
}

Fruit.find(function(err,fruits){
  mongoose.connection.close();

  if(err){
    console.log(err);
  }else{
    //  console.log(fruits);

    fruits.forEach(function(fruit){
      console.log(fruit.name);
    })
  }
})

Just a background : the fruits model has a array of objects (fruits) and each fruit has a name with the code above I am displaying only its name

I am confused abut how we are closing mongoose connection even before logging the text also read at a article that its a callback function so gets executed after completion after execution of all steps so another question is how I know wether its a callback or a normal function also if I had another function print to make it callback (for the loop) how do I make it i.e print Hello after logging all the name of fruits but writing before log statement of fruits name



Solution 1:[1]

I am confused abut how we are closing mongoose connection even before logging the text

The callback function gets called when the data has been read from the mongoose connection.

The data is passed to the fruits argument.

You don't need the connection to be open after the data is already in a local variable.


how I know wether its a callback or a normal function

Callback functions are normal functions. It is just how they are used. See MDN:

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Quentin