Reputation: 23
when I use deferred.resolve
way to promise a action,I can't get the content of the file
function readFile(fileName) {
var deferred = Q.defer();
fs.readFile(fileName, 'utf-8', deferred.resolve);
return deferred.promise;
};
readFile('test.txt').then(function (err, data) {
console.log('data:' + data)
})
I get data:undefined
output
but it works OK fine when I promised action httpGet
var httpGet = function (opts) {
var deferred = Q.defer();
http.get(opts, deferred.resolve);
return deferred.promise;
};
httpGet('http://www.google.com').then(function (res) {
console.log("Got response: " + res.statusCode);
res.on('data', function (data) {
console.log(data.toString());
})
}
);
Is there something wrong the code above and in this way how can i get the content of the file. or is there something different between fs.readFile and http.get?
Upvotes: 2
Views: 5772
Reputation: 276306
You can use Q.nfcall
to call a NodeJS function promisified.
function httpGet(opts){
return Q.nfcall(http.get,opts);
}
Or simply:
var httpGet = Q.nfbind(http.get,http)
This would also work for fs.readFile
by the way.
If you want to do it manually. Q's deferred objects have a .makeNodeResolver
function which lets you pass them around safely like you do:
var httpGet = function (opts) {
var deferred = Q.defer();
http.get(opts, deferred.makeNodeResolver());
return deferred.promise;
};
One of the things .makeNodeResolver
does is bind the .this
value.
It is better to use .nfcall
though.
Upvotes: 3