Here we look at how to implement the node API promise with Q.js.
First, everything is install
The code is as follows:
NPM Install Q
Second, the standard node style API Promise method
1. Use Q.nfcall
Relative to Q.fcall, Q.nfcall is node's q.fcall.
The code is as follows:
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
The code is as follows:
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
The code is as follows:
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 ()
The code is as follows:
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);
});