JavaScript/Promise experts,
I hope you can help me, because I don\'t understand how I can create a function that returns an existing promise instead of a new promise
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;
function notSoRandomAsyncNumber() {
if (!p)
p = new Promise(function(resolve) {
setTimeout(function() {
resolve(Math.random());
}, 1000);
});
return p;
}
Or, abstracted into a helper function:
function memoize(fn) {
var cache = null;
return function memoized(args) {
if (fn) {
cache = fn.apply(this, arguments);
fn = null;
}
return cache;
};
}
function randomAsyncNumber() {
return new Promise(res => {
setTimeout(() => resolve(Math.random()), 1000);
});
}
function randomAsyncNumberPlusOne() {
return randomAsyncNumber().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())