Suppose you have some data that comes from a web server somewhere. But, it doesn’t change – so we really only need to fetch it once, and then store the result for easy access (maybe its an Enum that you map to a list of key/value pairs). We can do this easily enough in a service, but if two calls are made to the service in rapid succession – that is, the second one comes in before the first one is done – I don’t want to hit the server twice for the same information. Since we’re returning a promise, its easy enough to set a local variable when the first call makes it in, allowing the second call to just wait a little bit via a setTimeout and then call the method again.
Here’s what I mean:
This function will return the cached version, wait a bit and try again if a fetch is already in progress, or fetch the items. I’ve used this pattern a few times with good success, so I figured it was worth writing down.