Is it an acceptable (not surprising) to use promises to cache results? The idea is to generate a promise once, and just return that same promise again on subsequent calls.
For example, a getAll() function that returns a promise would perform a time-intensive function only on the first call, and then return the same promise on repeat calls.
Example (in JavaScript, but I didn't actually try it, so more like pseudo-code):
var oldPromise = null;
function getAll() {
var newPromise;
if (!oldPromise) {
// first time called
newPromise = new Promise(function (resolve, reject) {
timeIntensiveFunction(function callback(data) {
resolve(data);
});
});
oldPromise = newPromise
return newPromise;
} else {
// already did it
return oldPromise;
}
}
getAll
would return a different promise on each call, you would be able to resolve as many times as you want(once per call togetAll
- but you can call it as many times as you want). To achieve the caching effect,getAll
needs to return the same promise object on every call, and for that caches the promise object in a closure variable. The promise is not used to implement a caching mechanism - a caching mechanism is already there and it'll work just fine withoutPromise
s.