File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ 'use strict' ;
2+
3+ const fs = require ( 'fs' ) ;
4+
5+ class Thenable {
6+
7+ constructor ( ) {
8+ this . thenHandler = null ;
9+ this . next = null ;
10+ }
11+
12+ then ( fn ) {
13+ this . fn = fn ;
14+ const next = new Thenable ( ) ;
15+ this . next = next ;
16+ return next ;
17+ }
18+
19+ resolve ( value ) {
20+ const fn = this . fn ;
21+ if ( fn ) {
22+ const next = fn ( value ) ;
23+ if ( next ) {
24+ next . then ( value => {
25+ this . next . resolve ( value ) ;
26+ } ) ;
27+ }
28+ }
29+ }
30+
31+ }
32+
33+ // Usage
34+
35+ const readFile = filename => {
36+ const thenable = new Thenable ( ) ;
37+ fs . readFile ( filename , 'utf8' , ( err , data ) => {
38+ if ( err ) throw err ;
39+ thenable . resolve ( data ) ;
40+ } ) ;
41+ return thenable ;
42+ } ;
43+
44+ readFile ( 'file1.txt' )
45+ . then ( data => {
46+ console . dir ( { file1 : data } ) ;
47+ return readFile ( 'file2.txt' ) ;
48+ } )
49+ . then ( data => {
50+ console . dir ( { file2 : data } ) ;
51+ return readFile ( 'file3.txt' ) ;
52+ } )
53+ . then ( data => {
54+ console . dir ( { file3 : data } ) ;
55+ } ) ;
You can’t perform that action at this time.
0 commit comments