Node.js 使用节点js的回调函数和正常函数之间的差异

Node.js 使用节点js的回调函数和正常函数之间的差异,node.js,nodejs-stream,nodejs-server,Node.js,Nodejs Stream,Nodejs Server,我在NodeJS中实现了回调函数。但我对回调函数有疑问。我在node js中尝试了两个函数:一个回调函数和另一个普通函数。两个函数我都尝试运行它给定的相同结果。我没有任何人解释我的代码 回调函数.js const MongoClient = require('mongodb').MongoClient; var ObjectId = require('mongodb').ObjectID // Connection URL var db =" " MongoClient.connect('m

我在NodeJS中实现了回调函数。但我对回调函数有疑问。我在node js中尝试了两个函数:一个回调函数和另一个普通函数。两个函数我都尝试运行它给定的相同结果。我没有任何人解释我的代码

回调函数.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()
}
});
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

如果调用相同的函数,结果是相同的

这不是一个正确的回调

回调是函数的异步等价物。回拨 函数在给定任务完成时调用。节点使重 使用回调。Node的所有api都是以这样的方式编写的: 它们支持回调

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

例1

函数泛型回调 { 洛海先生 回拨5CCAC2FD247AF0218CFCA5DD } 通用函数ID { 你好
}是的,我理解在正常函数中,它的同步工作意味着我在正常函数中输出了hai和hello,但我得到了hello和hai。很抱歉,我误解了这个概念,我给出的两个代码都是回调函数。它不是正常函数。