简体   繁体   中英

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. I guess that it is because B console is executed before getXXbyUsername because in getXXbyUsername callback I define 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. 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. In your code, XX.getXXByUsername is a database operation which is time consuming. So it proceeds to console.log("B: "+ " " + myObj); before completing the database operation and hence muObj is undefined. 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. In your case, 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.

Because callback in getXXByUsername() executes later than the code that goes after this function call. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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