I've been learning Node/Javascript, using promises from the start (I don't know how to not use promises and often wonder how others get along without them).
So I sometimes need to "promisify" simple stuff like reading a file with fs
:
var readFile = function(path) {
return new Promise(function(fulfill, reject) {
fs.readFile(path, function(err, data) {
if (err) { reject(err); }
else { fulfill(data); }
});
});
};
And that's been working great. Now I need to do the same with superagent
, but the chaining style it uses has me stuck.
var request = require('superagent');
request.get(...).set(...).set(...).end(callback); // stuck!
I'd like to replace the end()
method (or ignore it and add a new method) with one that returns a promise. Something like this...
var endQ = function() {
return new Promise(function(fulfill, reject) {
this.end(function(err, res) { // "this" is the problem!
if (err) { reject(err); }
else { fulfill(res); }
});
});
};
// then I could say this:
request.get(...).set(...).set(...).endQ().then(function(res) {
// happiness
}).catch(function(err) {
// sad about the error, but so happy about the promise!
});
This question here has all kinds of advice about adding methods to objects, but it's hard to see what is definitive. I was especially worried by this answer. Much of the advice centers around starting with the object's "class" and adding the function to .prototype
. Something like this....
// this part doesn't make sense
var requestInstance = new Request(); // no such thing in request as far as I know
requestInstance.prototype.endQ = endQ; // would be great, but no
See my problem? I want the JS equivalent of "subclassing" the request "class" and adding a method, but since its a module, I need to treat the request class as more or less opaque.
this
/ context inside a callback? – Hidrosis