当前位置: 首页 > 知识库问答 >
问题:

在catch中抛出一个错误,还是返回一个被拒绝的promise来冒泡异步函数中的错误,这样更好?[副本]

欧阳向文
2023-03-14

我在异步代码中使用async await,并希望将错误冒泡到异步函数中,该函数调用其中的另一个异步函数。我尝试了这个方法,效果很好,但是如果我在catch块iniside hi()中返回Promise.reject(新错误(“hi失败”))会更好吗?或者有更好的方法来实现这一点吗?

async function hi() {
  try {
    console.log("In hi");
    if (Math.random() < 0.5) throw new Error('error hi');
    else return Promise.resolve('hi resolved');
  } catch (error) {
    console.log("In hi error");
    throw error;
  } finally {
    console.log('hi finally');
  }
}

async function hey() {
  try {
    console.log("In hey");
    var data = await hi();
    console.log(data);
  } catch (error) {
    console.log("In hey error");
    console.log(error.message);
  }
}

hey();

共有1个答案

阮星火
2023-03-14

你可以试试这个:

function hi() {
    return new Promise((resolve, reject) => {
        console.log("In hi");
    if (Math.random() < 0.5) reject('error hi');
    else resolve('hi resolved');
    });
}

async function hey() {
  try {
    console.log("In hey");
    var data = await hi();
    console.log(data);
  } catch (error) {
    console.log("In hey error");
    console.log(error);
  }
}

hey();
 类似资料:
  • 问题内容: 我正在使用AWS JS SDK提供的承诺。创建包装AWS开发工具包的异步函数时的要点如下: 有人联系我,他说我永远不要在这类基于promise的函数中抛出错误。他们建议改为返回。老实说,我对承诺的了解还不是很深,所以他们的解释有点让我震惊。 问题答案: 他们是正确的。 调用假定始终都会返回一个承诺(并分别处理已解决和拒绝的承诺)。当您引发错误时,该函数不会返回promise。 您 可以

  • 我已经从http://hayageek.com/login-with-google-plus-javascript-api/ 我已经使用我的client_id,api密钥实现了代码,并且还遵循了Google oauth2中invalid_client的说明,但仍然收到相同的错误。 也在OAuth同意屏幕中并提及产品名称和电子邮件地址 错误:无效_client 应用程序:Project_Name 您

  • 在以下代码中: 在Promise api中使用(在中)和使用

  • 我试图利用es7异步功能,即。 在这里,所有promise*函数都进行ajax调用,并返回或如果ajax响应满足传递的参数,我相信我不能连续使用3个等待,因此需要一种方法来等待所有这些调用以某种方式返回它们的值。

  • 问题内容: 我正在尝试使用jQuery和Ajax,并且使用了这种方法。但是我收到错误$ .toJSON不是firebug中的函数。问题出在哪里?我使用jquery 1.3.2。谢谢 问题答案: 没错 没有功能:http : //api.jquery.com/jQuery.toJSON。也许您想使用它。