简体   繁体   English

为什么在节点中B在A之前执行?

[英]Why is B executed before A in node?

router.get('/xyz', function(req, res, next) {
  var myObj;

  XX.getXXByUsername("ee", function(err, doc){
    console.log("A: " + doc); //executes second, doc is object that I want

    myObj = doc; 

  });

  console.log("B: "+ " " + myObj); //executes first, myObj = undefined

  res.render("pr", {title: "XX", myObj: myObj});
});

Basicly, I am doing this because I want to send object to the jade template. 基本上,我这样做是因为我想将对象发送到玉模板。 I can get object in the A console, but in the B console myObj is undefined. 我可以在A控制台中获取对象,但是在B控制台中myObj是未定义的。 I guess that it is because B console is executed before getXXbyUsername because in getXXbyUsername callback I define myObj. 我猜这是因为B控制台在getXXbyUsername之前执行,因为在getXXbyUsername回调中定义了myObj。

I dont know if I explained what my problem is, but I am begginer and this is best explanation of problem that I can give. 我不知道我是否解释了我的问题,但是我是初学者,这是我可以给出的最好的解释。

Node js executes code asynchronously. Node js异步执行代码。 While code excution, if node comes across a task that takes some time to execute, it proceeds to the next line of code before completing this task. 在执行代码时,如果节点遇到需要花费一些时间才能执行的任务,则它会在完成此任务之前继续执行下一行代码。 This pattern is different from languages like PHP. 这种模式不同于PHP之类的语言。 In your code, XX.getXXByUsername is a database operation which is time consuming. 在您的代码中, XX.getXXByUsername是一项数据库操作,这很耗时。 So it proceeds to console.log("B: "+ " " + myObj); 因此它进入console.log("B: "+ " " + myObj); before completing the database operation and hence muObj is undefined. 在完成数据库操作之前,因此未定义muObj。 One way of solving this problem is by using callback functions. 解决此问题的一种方法是使用回调函数。 In node js, for every function, a call back is passed as an argument and the callback takes an error object as the first parameter and the result of the main function as the next argument. 在节点js中,对于每个函数,都将回调作为参数传递,并且回调将错误对象作为第一个参数,并将主函数的结果作为下一个参数。 In your case, doc . 就您而言, doc The callback gets executed only after the main function execution is completed. 仅在主函数执行完成后才执行回调。 So, in console.log("A: " + doc) , doc is the output of the XX.getXXByUsername function and hence it is not undefined. 因此,在console.log("A: " + doc) ,doc是XX.getXXByUsername函数的输出,因此它不是未定义的。

Because callback in getXXByUsername() executes later than the code that goes after this function call. 因为getXXByUsername()回调比该函数调用之后的代码执行晚。 In other words, the callback executes after your function retrieves the data (from database?). 换句话说,在函数从数据库中检索数据后执行回调。 Meanwhile the main function continues its execution, so you get B earlier than A . 同时main函数继续执行,因此您比A早得到B

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM