Reputation: 5358
I'm not quite sure I understand how errors are handled in promises (and I'm fairly new to promises so I'm likely not using them to their full potential).
I have the following code:
app.listenAsync = Promise.promisify(app.listen);
app.listenAsync(config.port)
.then(function done() {
console.log("We're listening!");
})
.catch(function (err) {
console.log("Abort abort!");
});
For a reason I don't quite understand, my catch()
is never called, even if app.listenAsync throws an error, EADDRINUSE for instance. Why?
Edit: I just noticed that if I do
var listenAsync = Promise.promisify(app.listen);
listenAsync(config.port)
.then(function done() {
console.log("We're listening!");
})
.catch(function (err) {
console.log("Abort abort!");
});
Gives almost the correct behaviour. listenAsync throws an error (that is caught in the catch
statement this time) Possibly unhandled TypeError: listener must be a function
. Am I missing something?
Upvotes: 2
Views: 817
Reputation: 140236
This has nothing to do with promises, it's just basic javascript: you are calling listen as if it was a function but it's a method of app
.
Some options:
Promise.promisifyAll(app);
// Note how it's called as a method on app
app.listenAsync(...).then(....)
Or
// Bind the function as a method of app
var appListenAsync = Promise.promisify(app.listen, app);
appListenAsync(...).then(....)
Upvotes: 4