-
Notifications
You must be signed in to change notification settings - Fork 1
/
async_memoize.js
44 lines (40 loc) · 934 Bytes
/
async_memoize.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* Memoize the below function
*/
function getSomeData(foo, callback) {
console.log("ASYNC REQ CALLED");
let uri = "https://jsonplaceholder.typicode.com/todos/" + foo;
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log("async request");
fetch(uri).then((res) => {
resolve(callback(undefined, res));
});
}, 300);
});
}
//
function memoize(fn) {
const cache = {};
return async function () {
const args = JSON.stringify(arguments);
cache[args] = cache[args] || fn.apply(this, arguments);
return cache[args];
};
}
const mem = memoize(getSomeData);
let cb = (err, res) => {
if (err) {
return err;
} else {
return res;
}
};
const x = mem(2, cb);
x.then((res) => {
return res.clone().json();
}).then((r) => console.log("A", r));
const y = mem(2, cb);
y.then((res) => {
return res.clone().json();
}).then((r) => console.log("B", r));