Regarding what a promise is and what problems it solves, please experience node's callback asynchronous coding method and move on to http://wiki.commonjs.org/wiki/Promises/A See It depends on how it is defined, so I won’t go into details here.
Here we look at how to use q.js to implement the promise of node api.
1. Everything starts with install
npm install q
2. Promise method of standard node style api
1. Use Q.nfcall
Relative to Q.fcall, Q.nfcall is the Q.fcall of node.
var FS = require('fs'),
Q = require('q'),
colors = require('colors'),
File = 'example.txt';
var fsReadFile = Q.nfcall(FS.readFile,file,encoding);
fsReadFile.then(function(result){
console.log((“invoke in nfcall ” file).red);
console.log(result.green);
},function(error){
console.log(“invoke in nfcall”.red);
console.log(error.toString().red);
}
);
2. Use Q.denodeify
var fsReadFile_denodeify = Q.denodeify(FS.readFile);
fsReadFile_denodeify(file,encoding).then(function(result){
console.log("invoke in denodeify".red);
console.log(result.green)
},function(error){
console.log("invoke in denodeify".red);
console.log(error.toString().red);
}
);
3. Use Q.deferd
var fsReadFile_deferd = function(file,encoding){
var deferred = Q.defer();
FS.readFile(file,encoding,function(error,result){
If(error){
deferred.reject(error.toString().red);
}
deferred.resolve(result);
});
return deferred.promise;
};
fsReadFile_deferd(file).then(function(result){
console.log("invoke in deferd".red);
console.log(result.toString().green);
},function(error){
console.log("invoke in deferd".red);
console.log(error.toString().red);
}
);
4. Use makeNodeResolver()
var fsReadFile_makeNodeResolver = function(file,encoding){
var deferred = Q.defer();
FS.readFile(file,encoding,deferred.makeNodeResolver());
Return deferred.promise;
};
fsReadFile_makeNodeResolver(file,encoding).then(function(result){
console.log("invoke in makeNodeResolver".red);
console.log(result.green);
},function(error){
console.log(error.toString().red);
});