DEV Community

Discussion on: Building custom hooks in React to fetch Data

 
ehaynes99 profile image
Eric Haynes • Edited

Note that the former reply was someone else, so no one "kept using 'old'". It is, in fact, older, but we can refer to it as "the .then syntax".

To each their own, but the allure of async/await is that the code reads exactly the same as it would if it were synchronous. There is a valid argument for consistency. E.g. it's pretty much universally accepted that we don't intermittently use callbacks for async, even if it would save a line or 2.

It's not "way more complex", either. It's slightly more verbose, and only in a rare set of cases. The .then syntax is only cleaner where you can constrain the action to lambda expressions and have at least 4 of them. As soon as you need a block for any of them, IMO it's rather messy. What is simply another line with async/await becomes a new function, another level of nesting, and a new scope. It takes a hit for readability when shorter than 4 as well, since formatters like prettier will inline:

myApi.getOrder(123).then(setOrder).catch(setError);
Enter fullscreen mode Exit fullscreen mode

So yes, in the cases where you have the catch in the same place as the call, can chain 4 or more operations that are all one liners, and never need to refer to something in a prior step of the chain, it's slightly cleaner, but it's rare enough that I wouldn't fault anyone for just forgetting about the syntax altogether.

const fetch1 = (orderNum) => {
  fetch(`/api/orders/${orderNum}`)
    .then((response) => response.json())
    .then(({ products }) => {
      setProducts(products);
      setError(null);
    })
    .catch((error) => {
      logger.error(error);
      setError(error);
    })
    .finally(() => setLoading(false));
};

// vs
const fetch2 = async (orderNum) => {
  try {
    const response = await fetch(`/api/orders/${orderNum}`);
    const { products } = await response.json();

    setProducts(products);
    setError(null);
  } catch (error) {
    logger.error(error);
    setError(error);
  }
  setLoading(false);
};
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
shifi profile image
Shifa Ur Rehman

And Finally!