Reputation: 5186
db.collection.findOne
is an async operation (MongoDB, but that doesn't really matter here), which is why I'm wrapping it in a promise here.
var letsDoSomething = new Promise(function(resolve, reject){
db.collection('stackoverflow').findOne({question: true}, function(err, question){
resolve(question); // let's pretend we found a question here, and it is now resolving
})
})
letsDoSomething.then(function(myData){ // it resolves
console.log('foo', bar); // since 'bar' is undefined, this should fail – why doesn't it? No error messages, it goes completely silent
});
Why doesn't the debugger throw an error when I try to log bar
, which simply doesn't exist? It just goes poof silent, not a word.
Expected result (in my mind):
console.log('foo', bar);
ReferenceError: bar is not defined
What am I missing?
Environment:
node -v
v0.12.4
Upvotes: 2
Views: 1689
Reputation: 239683
It is not swallowing that error, but if a then
or catch
handler results in an error, then the current promise will be rejected with that error.
In your case, ReferenceError
is thrown, but it rejects the promise. You can see the actual error being propagated, by attaching a catch
handler, like this
new Promise(function (resolve, reject) {
resolve(true);
})
.then(function (result) {
console.log(result, bar);
})
.catch(function (er) {
console.error('Inside Catch', er);
});
Now you will see
Inside Catch [ReferenceError: bar is not defined]
Further Reading:
Upvotes: 4