使用第一级 try ... catch 捕获 JavaScript Promise 中的错误 [英] Catching Errors in JavaScript Promises with a First Level try ... catch

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

问题描述

所以,我希望我的第一级捕获是处理错误的捕获.无论如何,是否可以将我的错误传播到第一个捕获?

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 语法 你可以做到这一点.请注意,在撰写本文时,并非所有浏览器都支持此功能,您可能需要使用 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);
  }
}

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

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