DEV Community

Discussion on: 5 Async/Await Design Patterns for Cleaner Async Logic

Collapse
 
saroj990 profile image
saroj sasmal

Nice Article!. IMO await with promise chaining is not ideal and should not be used at all. By default await statement will wait for the execution of the promise, so adding a then block is not required.

const res = await fetch('/users').
  then(res => {
    if (res.status < 200 || res.status >= 400) {
      throw new Error('Server responded with status code ' + res.status);
    }
    return res;
  }).
  then(res => res.json());
Enter fullscreen mode Exit fullscreen mode

The above statement can be simplified with a single await within a try/catch block like following

try {
  const res = await fetch('/users');
  if (res.status < 200 || res.status >= 400) {
    throw new Error('Server responded with status code ' + res.status);
  }
  const data = res.json();
  // do something with data
} catch(err) {
  // handle error
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
masteringjs profile image
Mastering JS

The problem is that you need to do await res.json() as well, but otherwise your approach works. I think the await fetch().then(res => res.json()) pattern is common enough that it's worth mentioning.