因此,我希望我的第一级捕获是处理错误的捕获。反正有没有将我的错误传播到第一个陷阱?
参考代码,尚不可用:
Promise = require('./framework/libraries/bluebird.js'); function promise() { var promise = new Promise(function(resolve, reject) { throw('Oh no!'); }); promise.catch(function(error) { throw(error); }); } try { promise(); } // I WANT THIS CATCH TO CATCH THE ERROR THROWN IN THE PROMISE catch(error) { console.log('Caught!', error); }
使用新的异步/等待语法,您可以实现此目的。请注意,在编写本文时,并非所有浏览器都支持此功能,您可能需要使用babel(或类似的东西)来转换代码。
// Because of the "async" keyword here, calling getSomeValue() // will return a promise. async function getSomeValue() { if (somethingIsNotOk) { throw new Error('uh oh'); } else { return 'Yay!'; } } async function() { try { // "await" will wait for the promise to resolve or reject // if it rejects, an error will be thrown, which you can // catch with a regular try/catch block const someValue = await getSomeValue(); doSomethingWith(someValue); } catch (error) { console.error(error); } }