Why does this promise silently fail?

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?


node -v



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) {
  .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:

  1. Why cannot I throw inside a Promise.catch handler?


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.