Nodejs asynchronous calls are sometimes the most troublesome, how can be some code order execution, here and everyone to share nodejs promise what is
promise
promise
A standard that describes the return result of an asynchronous call, including the correct return result and error handling. For detailed documentation, refer to promises/a+. At present, promise
there are many modules to implement the standard, such as Q, Bluebird and deferred, below we take the Q as an example, introduce how to use in the promise
nodejs
.
I looked for the use of promise, one of the most useful is q.js, personally feel. Of course, there are promise.js, interested friends can study, here is mainly about the use of q.js.
First Download Install q.js--
NPM Install Q
1 , using Q.nfcall
Q.nfcall is the q.fcall of node, relative to Q.fcall.
var require (' FS '),
require (' Q '),
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);
}
);
Q.fcall (function () {
return "1";
})
. then (function (value2) {
Console.log ("print", value2);
Return User.test (value2);
})
. then (function (VALUE3) {
Console.log (VALUE3);
Return "3";
})
. then (function (value4) {
Console.log (VALUE4);
Return "4";
})
. then (function (value4) {
Do something with Value4
Console.log ("Show:", value4);
})
. catch (function (error) {
Handle any error from the all above steps
})
. done ();
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 , using Q.deferd
var 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 , using Makenoderesolver ()
var 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);
});
Q.js Implementing Nodejs Sequential invocation