0

In my application, I get information from an API and cache it. If the cache misses and I end up retrieving the data to store it, when should I update the cache?

When a promise is executed, resolve does not stop the execution of the rest of the function. I want to return the information as soon as possible, so if I resolve the promise first, and then update the cache, would I actually reap any performance benefits? Or am I setting myself up for race conditions or something like that down the road?

This

new Promise((resolve, reject) => {
  let result = getThingFromApi();
  resolve(result);
  updateCache(result); // returns promise
})

or this?

new Promise((resolve, reject) => {
  let result = getThingFromApi();
  updateCache(result); // returns promise
  resolve(result);
})
Carson McManus
  • 314
  • 5
  • 10
  • 2
    Using an anti pattern if `getThingFromApi()` returns a promise. No need for `new Promise` also – charlietfl Sep 21 '19 at 19:04
  • Make sure to avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it) in case `getThingFromApi` returns a promise! – Bergi Sep 21 '19 at 19:08

2 Answers2

1

When a promise is executed, resolve does not stop the execution of the rest of the function. I want to return the information as soon as possible, so if I resolve the promise first, and then update the cache, would I actually reap any performance benefits? Or am I setting myself up for race conditions or something like that down the road?

No, it doesn't matter for performance at all. The resolve call doesn't do any actual work like invoking the promise callbacks, it only sets a flag that the promise is now resolved with a value and schedules the rest of the resolution work for later. resolve() is essentially asynchronous. And therefore it doesn't matter at all where you call it here, the asynchrony was introduced precisely to prevent these kind of race conditions.

The only worry you should have is that resolve(result) will not be executed if you place it afterwards and updateCache(result) does throw an exception.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

Store the promise in the cache and always return it!

A call for the data must necessarily be asynchronous anyway, since you don't know whether it's cached or not, so the caller must expect an asynchronous result. Storing the promise itself in the cache and returning the promise solves all synchronisation problems. If the data is not cached or outdated, you initiate the data retrieval and store the promise in the cache in the meantime. If another call for the same data is made, you can return the promise which will resolve as soon as the data arrives. If the promise has already resolved, the result can be immediately retrieved through .then.

deceze
  • 510,633
  • 85
  • 743
  • 889