我一直在读node初学者
我看到了下面两段代码。
第一个问题:
var result = database.query("SELECT * FROM hugetable");
console.log("Hello World");
第二点:
database.query("SELECT * FROM hugetable", function(rows) {
var result = rows;
});
console.log("Hello World");
我知道他们应该做什么,他们查询数据库来检索查询的答案。然后是console。log('Hello world')。
第一个应该是同步代码。
第二种是异步代码。
这两件作品之间的区别对我来说很模糊。输出是什么?
在谷歌上搜索异步编程也没什么用。
如果你在两个例子中都加上一行,这将变得更清楚:
var result = database.query("SELECT * FROM hugetable");
console.log(result.length);
console.log("Hello World");
第二点:
database.query("SELECT * FROM hugetable", function(rows) {
var result = rows;
console.log(result.length);
});
console.log("Hello World");
尝试运行这些程序,您将注意到第一个(同步)示例的结果。长度将在'Hello World'行之前打印出来。
在第二个(异步)示例中,结果。length将(很可能)打印在"Hello World"行之后。
这是因为在第二个例子中,数据库。查询在后台异步运行,脚本直接继续“Hello World”。console.log(result.length)只在数据库查询完成时执行。
同步编程
像C, c#, Java这样的编程语言是同步编程,所以无论你写什么,都会按照你写的顺序执行。
-GET DATA FROM SQL.
//Suppose fetching data take 500 msec
-PERFORM SOME OTHER FUNCTION.
//Performing some function other will take 100 msec, but execution of other
//task start only when fetching of sql data done (i.e some other function
//can execute only after first in process job finishes).
-TOTAL TIME OF EXECUTION IS ALWAYS GREATER THAN (500 + 100 + processing time)
msec
异步
NodeJs提供了异步特性,它本质上是非阻塞的,假设在任何需要时间的I/O任务(获取,写入,读取)中,NodeJs不会保持空闲状态并等待任务完成,它会开始执行队列中的下一个任务,每当该时间任务完成时,它会使用回调通知。
下面的例子会有所帮助:
//Nodejs uses callback pattern to describe functions.
//Please read callback pattern to understand this example
//Suppose following function (I/O involved) took 500 msec
function timeConsumingFunction(params, callback){
//GET DATA FROM SQL
getDataFromSql(params, function(error, results){
if(error){
callback(error);
}
else{
callback(null, results);
}
})
}
//Suppose following function is non-blocking and took 100 msec
function someOtherTask(){
//some other task
console.log('Some Task 1');
console.log('Some Task 2');
}
console.log('Execution Start');
//Start With this function
timeConsumingFunction(params, function(error, results){
if(error){
console.log('Error')
}
else{
console.log('Successfull');
}
})
//As (suppose) timeConsumingFunction took 500 msec,
//As NodeJs is non-blocking, rather than remain idle for 500 msec, it will start
//execute following function immediately
someOtherTask();
简而言之,输出如下:
Execution Start
//Roughly after 105 msec (5 msec it'll take in processing)
Some Task 1
Some Task 2
//Roughly After 510 msec
Error/Successful //depends on success and failure of DB function execution
区别很明显,同步将花费超过600 msec(500 + 100 +处理时间),异步可以节省时间。