Q模块实现NodeJS的Promise/A+规范
基于nodejs的q模块的作用,就是实现异步的回调,实现多异步的同步回调机制。
首先的引入q模块
npm install -g q //安装
一:编写具有Promise规范的代码
例如:
function readFile(path, encoding) {
var defer = Q.defer();
var file = fs.readFile(path, encoding, function (err, data) {
defer.resolve(data);
});
return defer.promise;
}
一:异步的方法的同步调用
function SyncTest() {
var read1 = readFile("d:/log.txt","utf8");//异步方法
var read2 = readFile("d:/log2.txt","utf8");//异步方法
Q.all([read1, read2]).then(function (msg) {
console.log("读取完成");
console.log(msg);//返回值也是读取文件内容的数值
}, function (error) {
console.log("读取错误");
console.log(error);
}, function (process) {
console.log(process);
});
}
Q.all的作用就是等待所有具有promise规范的异步代码执行完成之后,在执行,作用就是同步异步方法的返回结果。
上面的代码也可以这么调用
var read1 = readFile("d:/log.txt","utf8");//异步方法
read1.then(function(content){
console.log("文件1内容");
readFile("d:/log2.txt","utf8").then(function(content){
console.log("文件2内容");
});//在调用下一个异步方法
});
浙公网安备 33010602011771号