同步
同步代码异味着每次执行一个操作,在一个操作完成之前,代码的执行会被阻塞无法移动到下一个下一个操作
function sleep(milliseconds){
var start = new Date().getTime();
while((new Date().getTime()-start)<milliseconds){
}
}
function fetchPage(){
console.log('one');
sleep(2000);
console.log('sleep two');
}
function fetchApi(){
console.log('three ');
sleep(2000);
console.log('sleep four');
}
fetchPage();
fetchApi();
node.js几乎不使用同步而使用异步
异步
一旦调用无需等待,立即调用.并且是非阻塞的.两个函数会侦听远程服务器的返回,并以此触发回调函数.
var http = require('http');
function fetchPage(){
console.log('fetchPage');
http.get({host:'www.baidu.com',path:'/?delay-2000'},function(res){
console.log('date return from requesting page');
}).on('error',function(e){
console.log('There was an error '+e);
});
}
function fetchApi(){
console.log('fetchApi');
http.get({host:'www.baidu.com',path:'/?delay-2000'},function(res){
console.log('date return from requesting api');
}).on('error',function(e){
console.log('There was an error '+e);
})
}
fetchPage();
fetchApi();
函数的回调顺序无法保证,与网络有关