Member-only story

Asynchronous JavaScript — Part 4 of 4

Christopher Jeffery
2 min read4 days ago

--

Does caching Promises work?

Photo by Goashape Studio on Unsplash

We’re about to go deep and finish our conversation on Asynchronous JavaScript. When making multiple API requests, how do we decouple requests that depend on one another while ensuring everything is as performant as possible?

Two things, (1) Promise.all and (2) caching Promises. Promise.all enables making concurrent requests efficiently (it’s worth searching how it handles errors). Caching Promises allows us to decouple dependent requests while maintaining a performant and efficient request structure.

By combining these techniques, we can achieve an optimized and well-structured approach to handling multiple requests. An example, if we’re making calls a, b, and c, and c depends on a:

const getA = async (): Promise<A> => {
if cache.has('AKey')
return cache.get('AKey')

const promise = fetch('get-a') // get the Promise for caching
cache.set('AKey', promise)
return promise
}

const getB = async (): Promise<B> => {
return fetch('get-b')
}

const getC = async (): Promise<C> => {
const a = await getA()
return fetch(`/get-c/${a.id}`)
}

const getABC = async (): Promise<[A, B, C]> => {
return Promise.all([ getA(), getB(), getC() ])
}

From the example above, the order in which we call a, b, and c doesn’t matter. There are no duplicate requests, and no time is wasted unnecessarily waiting.

And there you have it — efficient, performant requests. To wrap up our journey, here’s a haiku from ChatGPT:

Promises align, swift
Concurrent flows intertwine,
Cache builds time refined.

Prev: Asynchronous JavaScript — Part 3 of 4

--

--

No responses yet