Memoization of promise-based function

javascript, memoization, promise

Solution

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".

Problem

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.

Original source

Related problems