3

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;
    }
}
3
  • 2
    This is not using promises as a caching mechanism - this is just caching promises.
    – Idan Arye
    Commented Apr 12, 2015 at 15:48
  • @IdanArye When you add the fact that you can only resolve a promise once, then the effect is to cache the results.
    – btilly
    Commented Apr 12, 2015 at 15:52
  • 1
    @btilly You can only resolve the returned promise once because the same promise is returned every time. If getAll would return a different promise on each call, you would be able to resolve as many times as you want(once per call to getAll - 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 without Promises.
    – Idan Arye
    Commented Apr 12, 2015 at 16:18

2 Answers 2

4

This is an absolutely sensible use of promises. Its one of the primary ways that promises are intended to be used.

The way that promises can have .then() added before or after being resolved is directly to allow this kind of usage. The point is that you might have the value right away, or it might not show up until some time later. In either case, the promise api runs the same way.

On the side, your code can be simplified

var promise = null;

function getAll() {
    if (!promise) {

        // first time called
        promise = new Promise(function (resolve, reject) {
            timeIntensiveFunction(function callback(data) {
                resolve(data);
            });
        });
    }
    return promise;
}

Or using lodash or underscore

getAll = _.memoize(function() {
   return new Promise(function (resolve, reject) {
       timeIntensiveFunction(function callback(data) {
           resolve(data);
       });
   });   
});
5
  • the _.memoize example doesn't work as far as my testing shows. _.memoize returns a "Function" so getAll() doesn't return a Promise, so can't be used with .then() at that point. so I don't quite see how this is meant to work. The goal is to write getAll().then(console.log('done')? Even when I do get this code to work, the promise returns immediately with 'undefined' (and I tested on code that was already working previous to adding _memoize)
    – PandaWood
    Commented Nov 8, 2017 at 23:57
  • I was missing a closing }) but after fixing that it works for me. See my pastebin here: pastebin.com/hM0JTqJG Commented Nov 9, 2017 at 0:45
  • You can't make getAll().then(console.log('done')) to work, you have to pass a function to then. Commented Nov 9, 2017 at 1:08
  • Right, appreciate the effort! Looks like I was returning the value of _.memoize instead of assigning a function name to it
    – PandaWood
    Commented Nov 9, 2017 at 3:43
  • You might want to consider some more cases: If the cached Promise has been rejected you might want to try again on the next call. I think it makes sense to wrap this into an own class to have a clearly defined behavior and not have to deal with all the edge cases all the time. Here is an example implementation (that goes some steps further): gist.github.com/karfau/bafcbf3aad9e7e7db5e447aae06fe237
    – karfau
    Commented Nov 6, 2023 at 4:49
-1

Well, calling a time intensive function within asynchronous flow is not acceptable because that blocks everything until it returns. That's the fundamental performance problem with cooperative multi-tasking.

Secondly, be sure to test possible flows with your actual promise library. Specifically test what happens if the promise is returned twice, and starts running twice, and tries to finish twice. Different promise libraries may do different things in this situation. The safe solution is to assume that it is up to you to avoid actually running the long thing twice, so you do not attempt to resolve twice.

Third, your snippet does not show where data arrives from. Be sure not to return the results of computing with the wrong set of data!

Fourth, if in doubt, comment on the purpose of what you are doing. Don't confuse the maintenance programmer!

Those are a lot of caveats. If you're comfortable with them, then this does seem to be a reasonable solution. I'd personally be inclined to more up front caching mechanisms which make it obvious what is going on. But this should work.

1
  • 2
    1) The time intensive function takes a callback, so I'd say its already taking care of the co-operation internally. 2) The code doesn't start the promise twice. 3) The data comes from the callback in the intensive code. No mystery there. Commented Apr 13, 2015 at 0:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.