Node.js 的异步机制由事件和回调函数——循环中的回调函数
2015-10-29 10:12
1081 查看
varfs=require('fs'); varfiles=['a.txt','b.txt','c.txt']; //for(vari=0;i<files.length;i++){ //事实上fs.readFile的回调函数中访问到的i值都是循环退出以后的 //原因是3次读取文件的回调函数事实上是同一个实例,其中引用到的i值是上面循环执行结束后的值 //fs.readFile(files[i],'utf-8',function(err,conetens){ //console.log(files[i]+":"+conetens); //}); //} for循环的输出结果: undefined:AAA undefined:BBB undefined:CCC //大多数情况下我们可以用数组的forEach方法解决这个问题 files.forEach(function(filename){ fs.readFile(filename,'utf-8',function(err,conetens){ console.log(filename+":"+conetens); }); }); forEach输出结果: a.txt:AAA b.txt:BBB c.txt:CCC
相关文章推荐
- node.js学习博客转载
- node个人博客第二天
- [116]Populating Next Right Pointers in Each Node
- Nodejs socket.io cliet对象结构
- node第二天
- 基于Node.js的自动化工具Gulp
- Mac上Hexo安装问题解决方法
- Mac上Hexo安装问题解决方法
- node.js_in_practice(intermediate)
- LeetCode 117: Populating Next Right Pointers in Each Node II
- hadoop datanode部分启动不了
- [LeetCode]Remove Nth Node From End of List
- LeetCode 116: Populating Next Right Pointers in Each Node
- Node.js与Express4安装与配置
- Node.js的开源、多进程实时WebSocket引擎:SocketCluster
- CCClipingNode的使用
- node.js npm常用命令
- 使用Node.js+Socket.IO搭建WebSocket实时应用
- NODEJS
- Node.js 4.0的ES6新特性