From 7024486ef0ca69019ecd1c35e8fb024012f0a4e2 Mon Sep 17 00:00:00 2001 From: PaIIadium Date: Wed, 21 Aug 2019 22:23:15 +0300 Subject: [PATCH 1/2] fixed resolve method --- JavaScript/9-thenable.js | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/JavaScript/9-thenable.js b/JavaScript/9-thenable.js index 3e6fe1d..dafd8cb 100644 --- a/JavaScript/9-thenable.js +++ b/JavaScript/9-thenable.js @@ -19,10 +19,8 @@ class Thenable { const fn = this.fn; if (fn) { const next = fn(value); - if (next) { - next.then(value => { - this.next.resolve(value); - }); + if (this.next) { + this.next.resolve(next); } } } @@ -41,7 +39,8 @@ const readFile = filename => { (async () => { - const file1 = await readFile('9-thenable.js'); + const file1 = await readFile('9-thenable.js').then(() => 5).then(() => 25); // Doesn`t work in old example + console.log(file1); console.dir({ length: file1.length }); })(); From 28388bcf369f95df971ff0d9a1e55f1bbaff18ac Mon Sep 17 00:00:00 2001 From: PaIIadium Date: Thu, 22 Aug 2019 17:54:32 +0300 Subject: [PATCH 2/2] Fixed resolve. Added some examples --- JavaScript/9-thenable.js | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/JavaScript/9-thenable.js b/JavaScript/9-thenable.js index dafd8cb..dac4433 100644 --- a/JavaScript/9-thenable.js +++ b/JavaScript/9-thenable.js @@ -15,10 +15,10 @@ class Thenable { return next; } - resolve(value) { + async resolve(value) { const fn = this.fn; if (fn) { - const next = fn(value); + const next = await fn(value); if (this.next) { this.next.resolve(next); } @@ -37,10 +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').then(() => 5).then(() => 25); // Doesn`t work in old example - console.log(file1); + 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); + })();