diff --git a/JavaScript/9-thenable.js b/JavaScript/9-thenable.js index 3e6fe1d..dac4433 100644 --- a/JavaScript/9-thenable.js +++ b/JavaScript/9-thenable.js @@ -15,14 +15,12 @@ class Thenable { return next; } - resolve(value) { + async resolve(value) { const fn = this.fn; if (fn) { - const next = fn(value); - if (next) { - next.then(value => { - this.next.resolve(value); - }); + const next = await fn(value); + if (this.next) { + this.next.resolve(next); } } } @@ -39,9 +37,26 @@ const readFile = filename => { return thenable; }; +const delay = fn => (...args) => { + const thenable = new Thenable(); + setTimeout(thenable.resolve.bind(thenable), 1000, fn(...args)); + return thenable; +}; + +const fn = val => val; +const mul = val => val * 5; +const add = val => val + 2; + +const fnDel = delay(fn); +const mulDel = delay(mul); +const addDel = delay(add); + (async () => { const file1 = await readFile('9-thenable.js'); console.dir({ length: file1.length }); + const res = await fnDel(7).then(mulDel).then(add).then(addDel); + console.log(res); + })();