This article mainly introduces node. use q. js implements api promise. promise is a standard that describes the returned results of asynchronous calls, including correct returned results and error handling, need a friend can refer to what is promise and promise solution is what problem, please experience node callback asynchronous coding method, along with the step http://wiki.commonjs.org/wiki/Promises/A to see how it is set, here I will not go into details.
Here we will look at how to use q. js to implement node api promise.
I. Everything starts with install
The Code is as follows:
Npm install q
Ii. Standard node style api promise Method
1. Use Q. nfcall
Compared with Q. fcall, Q. nfcall is the 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 );
});