Home >Web Front-end >JS Tutorial >Use q.js in node.js to implement promise of api_node.js

Use q.js in node.js to implement promise of api_node.js

WBOY
WBOYOriginal
2016-05-16 16:36:171314browse

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

Copy code The code is as follows:

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.

Copy code 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

Copy code 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

Copy code 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()

Copy code 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);
});
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn