为什么这个承诺默默地失败?
db.collection.findOne
是一个asynchronous操作(MongoDB,但在这里并不重要),这就是为什么我在这里包装它的承诺。
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 });
为什么当我尝试loginbar
,debugging器不会出现错误,这根本就不存在? 它只是沉默,而不是一个字。
预期的结果(在我看来):
console.log('foo', bar); ReferenceError: bar is not defined
我错过了什么?
环境:
node -v v0.12.4
它不会吞咽那个错误,但是如果一个then
或catch
处理程序导致错误,那么当前的promise将被拒绝并且出错。
在你的情况下, ReferenceError
被抛出,但它拒绝承诺。 你可以通过附加一个catch
处理程序来看到传播的实际错误
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]
进一步阅读:
- 为什么我不能在Promise.catch处理程序中抛出?