且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Nodejs MySQL连接查询返回值以调用函数

更新时间:2022-05-10 03:15:31

问题是这样的:

var r = db.demo(query, function(result) { data = result; });

console.log( 'Data : ' + data);

console.log将在调用回调函数之前运行,因为db.demo是异步的,这意味着可能要花一些时间才能完成,但是始终将代码的下一行console.log被执行.

The console.log will run before the callback function gets called, because db.demo is asynchronous, meaning that it might take some time to finish, but all the while the next line of the code, console.log, will be executed.

如果要访问结果,则需要等待回调函数被调用:

If you want to access the results, you need to wait for the callback function to be called:

var r = db.demo(query, function(result) { 
  console.log( 'Data : ' + result);
});

这是大多数处理I/O的代码将在Node中起作用的方式,因此了解它非常重要.

This is how most code dealing with I/O will function in Node, so it's important to learn about it.