接下来,我们看看有4个不同的I/O操作都在发生,他们都使用回调
Js代码
var fs = require('fs'),
http = require('http'); http.get({host:'www.baidu.com'},function(res){
console.log("baidu.com");
}).on('error',function(e){
console.log("Got error:" + e.message);
});
fs.readFile('somefile.txt','utf8',function(err,data){
if(err) throw err;
console.log("somefile");
});
http.get({host:'www.duokan.com'},function(res){
console.log("duokan.com");
}).on('error',function(e){
console.log("Got error:" + e.message);
});
fs.readFile('somefile2.txt','utf8',function(err,data){
if(err) throw err;
console.log("somefile2");
});
我们能知道哪个操作先返回吗?
猜测就是从磁盘上读取的两个文件先返回,因为无需进入网络,但是我们很难说哪个文件先返回,因为我们不知道文件的大小。对于两个主页的获取,脚本要进入网络,而响应时间则依赖于许多难以预测的事情,Node.js进程在还有已经注册的回调尚未触发之前将不会退出。回调首先解决不可预测性的方法,他也是处理并发(或者说一次做超过一件事情)的高效方法。
下面是我执行的结果

同步和异步代码
先看代码,同步(或者阻塞)代码
Js代码
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 returned from the api');
}
fetchPage();
fetchApi();
当脚本运行时,fetchPage()函数会被调用,直到它返回之前,脚本的运行是被阻塞的,在fetchPage()函数返回之前,程序是不能移到fetchApi()函数中的。这称为阻塞操作。
Node.js几乎从不使用这种编码风格,而是异步地调用回调。
看下下面编码,,
Js代码
var http = require('http'); function fetchPage(){
console.log('fetching page');
http.get({host:'www.baidu.com',path:'/?delay=2000'},
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');









