DEV Community

Discussion on: The only guide you'll ever need to understand Promises and Async await

Collapse
 
cherrydt profile image
David Trapp • Edited

You have a small mistake:

  .then((response) => {
    response.json()
  })
Enter fullscreen mode Exit fullscreen mode

...this won't work because it won't return the response.json() promise.

You need either...

  .then(response => response.json()) // without { }
Enter fullscreen mode Exit fullscreen mode

...or...

  .then(response => {
    return response.json()
  }
Enter fullscreen mode Exit fullscreen mode

Additionally, I find this confusing:

aPromise.then(( value) => {
  return value = 'changed value'
})
.then((value) => {
  console.log(value)
})
Enter fullscreen mode Exit fullscreen mode

There is no point in modifying the local variable value here as it's not used anymore anyway after this return. The following would work too:

aPromise.then((value) => {
  return 'changed value'
})
.then((value) => {
  console.log(value)
})
Enter fullscreen mode Exit fullscreen mode

...or alternatively aPromise.then(value => 'changed value').


One more mistake here - missing await:

const loadData = async () {
    const url = 'https://jsonplaceholder.com/todos/1/'
    const res = await fetch(url)
    const data = res.json() // << should have `await`
    console.log(data)
}
loadData()
Enter fullscreen mode Exit fullscreen mode

Also, this invites unhandled rejections. You should point out that you always need to append a .catch if you are calling an async function without await (and without storing/forwarding the returned promise)! Like this:

loadData().catch(e => console.error('Loading data failed:', e))
Enter fullscreen mode Exit fullscreen mode

In my book, anything that looks like this is automatically a bug.

async function whatever () { /* ... */ }

whatever() // BUG

await whatever() // okay
whatever().catch(e => { /* proper handling here */ }) // okay
return whatever() // okay if the caller handles rejected promises
const myPromise = whatever() // okay if myPromise gets a .catch somewhere else
Enter fullscreen mode Exit fullscreen mode

Note that a try/catch inside of the async function is not sufficient, because code inside the catch clause may itself throw an exception.

Collapse
 
rjitsu profile image
Rishav Jadon

Yeah you're right. Thanks for pointing it out