1

My teammate wrote the code:

const getItem = async () => { 
  const res = await axios.get('/items/123214324').then(r => 
  r.data.item).catch(err => console.log(err))

  return res
}

I think it absolute disaster(If we use async/await then we don't use then/catch, and vise versa). But he says it good. Who are right?

Gregory Kafanov
  • 339
  • 1
  • 3
  • 11
  • It is *recommended* to stick to either the promise API or `await`. But not *necessary*. There is no technical disadvantage from mixing both. The problem is that it might be slightly harder to read the code. The only problem here is that if there is a problem, you *only* get a log in the console but the `await` will continue. Perhaps that is OK. Perhaps not. But it's the only potentially incorrect thing in the code. – VLAZ Aug 14 '21 at 13:32
  • harder to read the code - the main reason not to use it... – Gregory Kafanov Aug 14 '21 at 13:34
  • So the rule is if you want to do it - just do, if you want readable code - just don't do it. – Gregory Kafanov Aug 14 '21 at 13:38
  • 2
    There is one problem here that the error doesn't get passed down the chain. So the catch shown will returned `undefined` to the `getData().then()` – charlietfl Aug 14 '21 at 13:41
  • 1
    Mixing the two doesn't necessarily mean the code is harder to read. IMO `data = await fetch(url).then(r => r.json())` is more readable than `result = await fetch(url); data = await result.json();` or even `data = await (await fetch(url)).json()`. It's mostly a matter of opinion. The general recommendation is just that - a recommendation, not a rule. – VLAZ Aug 14 '21 at 13:41
  • "*But he says it good.*" - ask him [why he used `await` here](https://stackoverflow.com/q/43353087/1048572) (instead of just `return axios.get(…).then(…).catch(…);`). If he can come up with a convincing reason, it might be good. I doubt he can. – Bergi Aug 14 '21 at 16:10
  • You shouldn't call it a "disaster" - the code works. (Apart from the glaring issue that it swallows errors and returns `undefined`, as pointed out also by @charlietfl). But yes, it certainly [violates best practices of `async`/`await` usage](https://stackoverflow.com/a/54387912/1048572). – Bergi Aug 14 '21 at 16:14

0 Answers0