为什么这个承诺默默地失败了? [英] Why does this promise silently fail?

查看:48
本文介绍了为什么这个承诺默默地失败了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

db.collection.findOne 是一个异步操作(MongoDB,但这在这里并不重要),这就是我在这里将它包装在一个 promise 中的原因.

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
});

当我尝试记录根本不存在的 bar 时,为什么调试器不会抛出错误?它只是沉默,一句话也不说.

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

我错过了什么?

环境:

node -v
v0.12.4

推荐答案

它并没有吞下那个错误,但是如果 thencatch 处理程序导致错误,那么当前的承诺将因该错误而被拒绝.

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.

在你的情况下, ReferenceError 被抛出,但它拒绝了承诺.通过附加一个 catch 处理程序,您可以看到正在传播的实际错误,就像这样

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);
  });

现在你会看到

Inside Catch [ReferenceError: bar is not defined]

<小时>

进一步阅读:


Further Reading:

  1. 为什么我不能在 Promise.catch 处理程序中抛出?

这篇关于为什么这个承诺默默地失败了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆