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

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

user770
1#
user770 Published in May 21, 2018, 6:39 pm

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.

You need to login account before you can post.

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

© 2016 Powered by mzan.com design MATCHINFO