使用节点js的回调函数和普通函数之间的区别

difference between call back function and normal function using node js

我在node js中实现了回调函数。但我对回调有疑问 function.I 在 node js 中尝试了两个函数,一个是回调函数,另一个是正常的 function.both 函数,我尝试 运行 它给定的相同 result.I 没有人解释我的代码。

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()
}
});

它同时显示结果 hello 和 hai

如果你调用同一个函数,结果是一样的。

这不是正确的回调。

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.

在你的情况下,你正在同步执行事情。 您只能在另一个函数的参数中使用它的指针来调用一个函数。

示例 1

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

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

示例 2

gener()

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

function gener()
{
    console.log("hai")
    data()
}