allencoded allencoded - 2 months ago 12
Javascript Question

Async / Await JS Catch not working in try/catch

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

Answer

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