How can I memoize a promise-based function?
Would straightforward memoization of the function suffice?
function foo() {
return new Promise((resolve, reject) => {
doSomethingAsync({ success: resolve, fail: reject });
});
};
Would this suffice?
var fooMemoized = memoize(foo);
Note: this question has been updated to remove the deferred anti-pattern.
Yes, that will suffice. Promises are simple return values, which is their great benefit - in contrast to callbacks, where memoisation code would be horrible.
You only might want to make sure that the memoized promise is uncancellable, if your promise library does support some kind of cancellation. Also notice that this form of memoisation remembers rejections as well, so you can't recover from errors by "trying again".
For promises simple sync memoize will not be good, because in most of cases you will not wish to memoize errors (rejected promises).
I did a simple library for common needs: https://github.com/nodeca/promise-memoize
Pseudo code:
let db = require('mongoose').createConnection('mongodb://localhost/forum');
function lastPosts(limit) {
return db.model('Post').find()
.limit(limit).orderBy('-_id').lean(true).exec(); // <- Promise (thenable)
}
let cachedLastPosts = require('promise-memoize')(lastPosts, { maxAge: 60000 });
// Later...
cachedLastPosts(10).then(posts => console.log(posts));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With