登峰造极境

  • WIN
    • CSharp
    • JAVA
    • OAM
    • DirectX
    • Emgucv
  • UNIX
    • FFmpeg
    • QT
    • Python
    • Opencv
    • Openwrt
    • Twisted
    • Design Patterns
    • Mysql
    • Mycat
    • MariaDB
    • Make
    • OAM
    • Supervisor
    • Nginx
    • KVM
    • Docker
    • OpenStack
  • WEB
    • ASP
    • Node.js
    • PHP
    • Directadmin
    • Openssl
    • Regex
  • APP
    • Android
  • AI
    • Algorithm
    • Deep Learning
    • Machine Learning
  • IOT
    • Device
    • MSP430
  • DIY
    • Algorithm
    • Design Patterns
    • MATH
    • X98 AIR 3G
    • Tucao
    • fun
  • LIFE
    • 美食
    • 关于我
  • LINKS
  • ME
Claves
长风破浪会有时,直挂云帆济沧海
  1. 首页
  2. Programming
  3. Node.js
  4. 正文

Node.js速学之-回调触发

2015-12-30
参考文献:[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、长时间运行的操作,必须移到另一个进程中。

标签: 暂无
最后更新:2016-01-24

代号山岳

知之为知之 不知为不知

点赞
下一篇 >

COPYRIGHT © 2099 登峰造极境. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

蜀ICP备14031139号-5

川公网安备51012202000587号