Node.js速学之-回调触发

参考文献:[1][EN]Georgo Ornbo.傅强.陈宗斌. Node.js入门经典[M]. 北京:人民邮电出版社.2013.4-1

Node.js 到处使用回调,尤其I/O操作。
示例一:网络I/O回调
Node.js 回调调用发生在远程服务器发出响应之后

var http = require('http');//请求http模块
http.get({host:'www.baidu.com'},function(res){
    console.log("Got Response:"+res.statusCode);
}).on('error',function(e){
    console.log("Got error:"+ e.message);
});

 

示例二、同步异步
1、同步

function sleep(milliseconds)
{
var start = new Date().getTime();
while((new Date().getTime()-start)<milliseconds)
{}
}
function fetchPage()
{
console.log("fetching page");
sleep(2000);
console.log("data returned from requesting page");

}
function fetchApi()
{
console.log("fetching api");
sleep(2000);
console.log('data return from the api');
}
fetchPage();
fetchApi();

程序返回:
fetching page
data returned from requesting page//2000毫秒后
fetching api
data return from the api//又格2000毫秒后
2、异步

var http = require('http');
function fetchPage()
{
console.log('fetching page');
http.get({host:'www.baidu.com',path:'/'},function(res){
console.log('data returned from requesting page');
}).on('error',function(e){console.log('There was an error' +e);
});
}
function fetchapi()
{
console.log('fetching api');
http.get({host:'www.baidu.com'},function(res){
console.log('date returned form the api');
}).on('error',function(e){
console.log("There was an error"+e);
});
}
fetchPage();
fetchapi();

程序返回:
fetching page
fetching api
date returned form the api
data returned from requesting page
三、原理
1、事件循环
事件循环使得系统可以将回调函数先保存起来,当事件在将来发生时再运行。
游戏规则:
1、函数必须快速返回
2、函数不得阻塞
3、长时间运行的操作,必须移到另一个进程中。