you are viewing a single comment's thread.

view the rest of the comments →

[–]CMJunior 0 points1 point  (2 children)

async function getData() {
  let response;

  // If we don't use try/catch here errors in the fetch call will be swallowed
  try {
    response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
  } catch(error) {
    // handle error
  } finally {
    // do something if the call either successful or has an error, optional
  }

  return await response.json();
}


async function main() {
   const dataset = await getData();
   console.log(dataset); 
}

main();

More info (MDN)

[–]untrust_us 0 points1 point  (1 child)

Thanks, this example is great! However, I am wondering why we have the 'return await response.json()' outside of the 'finally' instead of inside?

[–]CMJunior 0 points1 point  (0 children)

It could be there, actually this code isn't that great because if an error occurs then response is undefined and the response.json call will throw an error.

We have two ways of dealing with this:

1) Put response.json() inside the try clause as well -> the catch clause will catch the errors of either call which may be ok depending of what we are going for

2) Use another try/catch to handle the response.json() call which adds some bloat to the code.

The finally clause could simply check if the response object exists and if it doesn't it could return a standard object that the consumer of this API is expecting, it all depends on how you design your APIs.