Here we will look at how to use q. js to implement node api promise.
1. Everything starts with install
Npm install q
2. 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: |
Copy code |
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: |
Copy code |
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: |
Copy code |
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: |
Copy code |
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 ); }); |