0

I implement callback function in node js. but I have doubt in callback function.I tried two function in node js one callback function and another normal function.both function i tried to run its given same result.I do no any one explain my code.

callback_function.js

const MongoClient = require('mongodb').MongoClient;
var ObjectId = require('mongodb').ObjectID

// Connection URL
var db =" "

MongoClient.connect('mongodb://localhost:27017', (err, client) => {
  // Client returned
  db = client.db('olc_prod_db');

  gener(function(id)
{
    db.collection('Ecommerce').find({ _id: new ObjectId(id) }, function(err,result)
    {
        console.log("hello")
    })
})


function gener(callback)
{
    db.collection('Ecommerce').find({}).toArray(function(err,result)
    {
        console.log("hai")
    })
    callback("5ccac2fd247af0218cfca5dd")
}
});

normal_function.js

const MongoClient = require('mongodb').MongoClient;
var ObjectId = require('mongodb').ObjectID

// Connection URL
var db =" "

MongoClient.connect('mongodb://localhost:27017', (err, client) => {
  // Client returned
  db = client.db('olc_prod_db');

  gener()


  function data()
  {
      console.log("hello")
  }


function gener()
{
    db.collection('Ecommerce').find({}).toArray(function(err,result)
    {
        console.log("hai")
    })
    data()
}
});

it showing both result hello and hai

smith hari
  • 437
  • 1
  • 11
  • 22

1 Answers1

1

If you are calling the same function the result is the same.

That's not a proper callback.

Callback is an asynchronous equivalent for a function. A callback function is called at the completion of a given task. Node makes heavy use of callbacks. All the APIs of Node are written in such a way that they support callbacks.

In your case you are executing things synchronously. You only call a function using it's pointer in a parameter of another function.

Example1

function gener(callback)
{  
    console.log("hai")
    callback("5ccac2fd247af0218cfca5dd")
}

gener(function(id)
{   
        console.log("hello")
})

Example2

gener()

function data()
{
    console.log("hello")
}

function gener()
{
    console.log("hai")
    data()
}
MauroAlmeida
  • 218
  • 1
  • 2
  • 11
  • yes I understand in normal function its working synchronously means Actually I have output hai and hello in normal function but i got hello and hai. – smith hari May 07 '19 at 12:40
  • 1
    Sorry I mis understand concept,I given both code is call back function .its not normal function. – smith hari May 07 '19 at 12:52