Is it OK to Use Promises for Caching in JavaScript?

es6javascript

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;
    }
}

Best Answer

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);
       });
   });   
});
Related Topic