DEV Community

Discussion on: Cache API in JavaScript - with just 20 lines of code.

Collapse
 
lezzowski profile image
Omid

Can I ask you why are you doing this:

await fetch(url)
    .then(response => response.json())
    .then(json => cache[url] = {time: new Date(), value: json})
Enter fullscreen mode Exit fullscreen mode

Instead of this:

const response = await fetch(url)
cache[url] = { time: new Date(), value: response.json()
Enter fullscreen mode Exit fullscreen mode

If you use await you can replace those .then and I think this is much more cleaner :D

Collapse
 
rajeshroyal profile image
Rajesh Royal

Good Improvement. I will update the code.

Collapse
 
lezzowski profile image
Omid • Edited

I think you can append .json() to this:

const response = await fetch(url).json()
Enter fullscreen mode Exit fullscreen mode

(I didn't test it but I think it should work)
Happy to help you! :D

Thread Thread
 
rajeshroyal profile image
Rajesh Royal

No it cannot be done.

Thread Thread
 
gohomewho profile image
Gohomewho

Actually that doesn't work and you'll get an error.
Uncaught TypeError: fetch(...).json is not a function
Because fetch() return a promise, and it doesn't have a json method on it.

It should be like this.

const url = "https://jsonplaceholder.typicode.com/todos/1"
const data = await fetch(url).then((response)=>response.json())
Enter fullscreen mode Exit fullscreen mode

or this

const response = await fetch(url)
const data = await response.json()
Enter fullscreen mode Exit fullscreen mode

Note that calling response.json() also return a promise so you need to await it to get the result.