【问题标题】:Async / Await JS Catch not working in try/catch异步/等待 JS Catch 在 try/catch 中不起作用
【发布时间】:2017-02-06 17:19:16
【问题描述】:

我在下面有一点 javascript。在我们的 ES6 项目中使用 async/await。我注意到现在突然之间没有 404 响应代码。事实上 .json() 也抛出了一个控制台错误,但仍然没有抓住问题。我希望尝试中的任何错误都会立即抛出并转到代码的 catch 块。

async getDash(projectId, projectUserId) {
  try {
    const events = (await this.apiHttp
      .fetch(`${projectId}/users/${projectUserId}/participant-event-dash`)).json();
    return events;
  } catch (e) {
    // fail back to local (dev testing)
    return (await this.http
      .fetch(`${this.appConfig.url}dist/api/query/json/partic-event-dash.json`)).json();
  }
}

【问题讨论】:

  • 仅供参考,async/await 不是 ES6 的一部分。它将(很可能)成为明年发布的规范的一部分。

标签: javascript asynchronous async-await try-catch ecmascript-2017


【解决方案1】:

如果json()方法是异步的,你应该多加一个await:

async getDash(projectId, projectUserId) {
  try {
    const events = await (await this.apiHttp
      .fetch(`${projectId}/users/${projectUserId}/participant-event-dash`)).json();
    return events;
  } catch (e) {
    // fail back to local (dev testing)
    return await (await this.http
      .fetch(`${this.appConfig.url}dist/api/query/json/partic-event-dash.json`)).json();
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 2019-02-11
    • 2016-01-26
    • 2018-12-20
    相关资源
    最近更新 更多