nodejs作为使用Javascript为主要开发语言的服务器端编程技术和平台,而她最有特色的便是异步IO和事件驱动。而往往在我们进行编程的时候,就是会想着一些同步事件进行,比如说一个函数中可能出现闭包或者文件读取操作之类的问题就会引起异步进行,那么有办法让我们的程序按照我们想要的顺序进行吗?答案肯定是有的!!!
在接触一些nodejs编写的项目中,就碰到过这种问题,然后所幸大神传授方法,那么不卖关子了,那就是nodejs的一些模块: co、async、promise等,接下来我简单的一一列举。
promise:
$.get('/api/data').then(function(data) { console.log(data); return $.get('/api/user');})
.then(function(user) { console.log(user); return $.get('/api/products');})
.then(function(products) { console.log(products);});
co:
var co = require('co');
co(function *() {
yield sayhello();
yield sayworld();
yield saybye();});
co模块参考:https://blog.youkuaiyun.com/whitehack/article/details/52133035
async: Async提供了大约20个函数,包括常用的 map, reduce, filter, forEach 等,异步流程控制模式包括,串行(series),并行(parallel),瀑布(waterfall)等。
async的相关学习可以参考 https://www.jianshu.com/p/b6ed67e57844