Home Do I need to create a Promise object for a failed async fetch?
Reply: 1

Do I need to create a Promise object for a failed async fetch?

Kokodoko
1#
Kokodoko Published in 2018-02-12 14:40:33Z

I am using async await to call fetch, but it's not clear to me how to reject the result, and what to return, if the fetch fails. (for example, because the url is incorrect).

async loadJSON(url) {
  try {
      let res = await fetch(url)
      return res.json()
  } 
  catch (err) {
      // do I need to create a new promise here and reject it?
      // or can I just return false?
      return // erm...
  }
}

// calling the function, preferably without using try catch here
let result = await loadJSON("bla.php")

EDIT

I would like all my fetch and error handling code to be inside loadJSON, so I don't need to sprinkle try catch everywhere around my app.

aashah7
2#
aashah7 Reply to 2018-02-12 15:21:23Z

I would write it like this:

function loadJson(url) {
  return fetch(url)
  .then(res => res.json())
  .then(data => ({ isSuccess: true, data }))
  .catch(error => ({ isSuccess: false, error }))
}

And then:

let result = await loadJson("bla.php")

And then:

if (result.isSuccess) {
  // result.data
} else {
  // result.error 
}

Or:

return result.isSuccess ? result.data : result.error
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.375767 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO