How To Create A Function That Returns An Existing Promise Instead Of New Promise?
Solution 1:
You'll want to memoise the promise, not the value that it resolves with. Memoisation works fine with promises as result values.
var p = null;
functionnotSoRandomAsyncNumber() {
if (!p)
p = newPromise(function(resolve) {
setTimeout(function() {
resolve(Math.random());
}, 1000);
});
return p;
}
Or, abstracted into a helper function:
functionmemoize(fn) {
var cache = null;
returnfunctionmemoized(args) {
if (fn) {
cache = fn.apply(this, arguments);
fn = null;
}
return cache;
};
}
functionrandomAsyncNumber() {
returnnewPromise(res => {
setTimeout(() =>resolve(Math.random()), 1000);
});
}
functionrandomAsyncNumberPlusOne() {
returnrandomAsyncNumber().then(n => n+1);
}
var notSoRandomAsyncNumber = memoize(randomAsyncNumber);
var notSoRandomAsyncNumberPlusOne = memoize(randomAsyncNumberPlusOne);
(notice that notSoRandomAsyncNumberPlusOne
still will create a randomAsyncNumber()
on the first call, not a notSoRandomAsyncNumber()
)
Solution 2:
Try the new variable approach suggested. Promises are designed to be single-shot, so it depends on the implementation. What you are trying to do is more in the arena of events or reactivex. If you are using jquery then you can use their event scheme. A cleaner one is available on the nodejs site. Since it does not require anything else it runs in the browser. rxjs is the cream of the stream processing crop, but it is a big library and requires some learning. Worth it - since the same knowledge is useful client and server in many languages. You can even set up a stream from a promise - among many other ways.
Post a Comment for "How To Create A Function That Returns An Existing Promise Instead Of New Promise?"