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()
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))
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
Note that a try/catchinside of the async function is not sufficient, because code inside the catch clause may itself throw an exception.
You have a small mistake:
...this won't work because it won't return the
response.json()
promise.You need either...
...or...
Additionally, I find this confusing:
There is no point in modifying the local variable
value
here as it's not used anymore anyway after thisreturn
. The following would work too:...or alternatively
aPromise.then(value => 'changed value')
.One more mistake here - missing
await
:Also, this invites unhandled rejections. You should point out that you always need to append a
.catch
if you are calling anasync
function withoutawait
(and without storing/forwarding the returned promise)! Like this:In my book, anything that looks like this is automatically a bug.
Note that a
try
/catch
inside of theasync
function is not sufficient, because code inside thecatch
clause may itself throw an exception.Yeah you're right. Thanks for pointing it out