最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AsyncAwait JS Catch not working in trycatch - Stack Overflow

programmeradmin1浏览0评论

I have the bit of javascript below. Using async/await in our ES6 project. I have noticed that now all of a sudden a 404 response code isn't hitting the catch. In fact the .json() is also throwing a console error but still not hitting the catch. I would expect any error in the try to immediately throw and go to the catch block of code.

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

I have the bit of javascript below. Using async/await in our ES6 project. I have noticed that now all of a sudden a 404 response code isn't hitting the catch. In fact the .json() is also throwing a console error but still not hitting the catch. I would expect any error in the try to immediately throw and go to the catch block of code.

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();
  }
}
Share Improve this question edited Sep 28, 2016 at 16:01 Felix Kling 818k181 gold badges1.1k silver badges1.2k bronze badges asked Sep 28, 2016 at 15:57 allencodedallencoded 7,30517 gold badges75 silver badges133 bronze badges 1
  • 1 FYI, async/await is not part of ES6. It will (most likely) be part of the spec released next year. – Felix Kling Commented Sep 28, 2016 at 16:02
Add a ment  | 

1 Answer 1

Reset to default 6

If the json() method is asynchronous, you should add one more 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();
  }
}
发布评论

评论列表(0)

  1. 暂无评论