使用First Level try ... catch捕获JavaScript承诺中的错误 [英] Catching Errors in JavaScript Promises with a First Level try ... catch

查看:137
本文介绍了使用First Level try ... catch捕获JavaScript承诺中的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我希望我的第一级抓捕能够处理错误。无论如何将我的错误传播到第一次捕获?

So, I want my first level catch to be the one that handles the error. Is there anyway to propagate my error up to that first catch?

参考代码,但尚未工作:

Reference code, not working (yet):

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


推荐答案

使用新的 async / await syntax 您可以实现此目的。请注意,在撰写本文时,并非所有浏览器都支持此操作,您可能需要使用 babel 来转换代码(或者类似的东西)。

With the new async/await syntax you can achieve this. Please note that at the moment of writing this is not supported by all browsers, you probably need to transpile your code with babel (or something similar).

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

这篇关于使用First Level try ... catch捕获JavaScript承诺中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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