Write a function named cacheGetResult
that receives one parameter
getPromise
that returns a Promise used to compute some result. The Promise will take a bit of time to resolve, let's assume a minimum of 1 second.The cacheGetResult
function should return another function, let's call this one getResult
.
The getResult
function should return a Promise that resolves to the same result as getPromise
. However, multiple calls to the getResult
function should not re-compute the result. The result should be computed only once and then cached for subsequent calls.
const getResult = cacheGetResult(getPromise);
getResult()
.then((result) => {
console.log(result); // Prints "Hello, world!" after 1 second"
return getResult();
})
.then((result2) => {
console.log(result2); // Prints "Hello, world!" immediately, because the result was cached
});
function getPromise() {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Hello, world!");
}, 1000);
});
}