The difference is that in the first example , the program will block in the first line.(区别在于,在第一个示例中 ,程序将在第一行中阻塞。)
The next line ( console.log
) will have to wait.(下一行( console.log
)必须等待。)
In the second example , the console.log
will be executed WHILE the query is being processed.(在第二个示例中 ,将在处理查询时执行console.log
。) That is, the query will be processed in the background, while your program is doing other things, and once the query data is ready, you will do whatever you want with it.(也就是说,查询将在后台处理,而您的程序正在执行其他操作,并且一旦查询数据准备就绪,您就可以使用它进行任何操作。)
So, in a nutshell: The first example will block, while the second won't.(简而言之:第一个示例将阻止,而第二个示例则不会。)
The output of the following two examples:(以下两个示例的输出:)
// Example 1 - Synchronous (blocks)
var result = database.query("SELECT * FROM hugetable");
console.log("Query finished");
console.log("Next line");
// Example 2 - Asynchronous (doesn't block)
database.query("SELECT * FROM hugetable", function(result) {
console.log("Query finished");
});
console.log("Next line");
Would be:(将会:)
Query finished
Next line
Next line
Query finished
Note(注意)
While Node itself is single threaded , there are some task that can run in parallel.(尽管Node本身是单线程的 ,但有些任务可以并行运行。) For example, File System operations occur in a different process.(例如,文件系统操作在不同的过程中发生。)
That's why Node can do async operations: one thread is doing file system operations, while the main Node thread keeps executing your javascript code.(这就是为什么Node可以执行异步操作的原因:一个线程在执行文件系统操作,而Node的主线程一直在执行您的JavaScript代码。) In an event-driven server like Node, the file system thread notifies the main Node thread of certain events such as completion, failure, or progress, along with any data associated with that event (such as the result of a database query or an error message) and the main Node thread decides what to do with that data.(在节点等事件驱动服务器中,文件系统线程将某些事件(例如完成,失败或进度)以及与该事件关联的任何数据(例如数据库查询或错误的结果)通知主节点线程。消息),然后由主节点线程决定如何处理该数据。)
You can read more about this here: How the single threaded non blocking IO model works in Node.js(您可以在此处了解更多信息: 单线程无阻塞IO模型如何在Node.js中工作) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…