同步编程
诸如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
异步
NodeJ具有异步功能,它本质上是非阻塞的,假设在任何需要花费时间(读取,写入,读取)的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(500 + 100 +处理时间)毫秒,异步可以节省时间。