File tree Expand file tree Collapse file tree 2 files changed +92
-0
lines changed Expand file tree Collapse file tree 2 files changed +92
-0
lines changed Original file line number Diff line number Diff line change
1
+ 'use strict' ;
2
+
3
+ // Task: implement cancel using AbortController,
4
+ // AbortSignal, or passing `timeout` as an option
5
+
6
+ const promisify = ( fn ) => ( ...args ) => {
7
+ const promise = new Promise ( ( resolve , reject ) => {
8
+ const callback = ( err , data ) => {
9
+ if ( err ) reject ( err ) ;
10
+ else resolve ( data ) ;
11
+ } ;
12
+ fn ( ...args , callback ) ;
13
+ } ) ;
14
+ return promise ;
15
+ } ;
16
+
17
+ // Usage
18
+
19
+ const fs = require ( 'node:fs' ) ;
20
+ const read = promisify ( fs . readFile ) ;
21
+
22
+ const main = async ( ) => {
23
+ const fileName = '1-promisify.js' ;
24
+ const data = await read ( fileName , 'utf8' ) ;
25
+ console . log ( `File "${ fileName } " size: ${ data . length } ` ) ;
26
+ } ;
27
+
28
+ main ( ) ;
Original file line number Diff line number Diff line change
1
+ 'use strict' ;
2
+
3
+ // Task: implement ability to use Timer in multiple places
4
+ // In usage section we have 3 sections with async iterators
5
+ // generated from single timer, just last sections iterates
6
+ // as of now. Fix this to allow all sections to iterate
7
+
8
+ class Timer {
9
+ #counter = 0 ;
10
+ #resolve = null ;
11
+
12
+ constructor ( delay ) {
13
+ setInterval ( ( ) => {
14
+ this . #counter++ ;
15
+ if ( this . #resolve) {
16
+ this . #resolve( {
17
+ value : this . #counter,
18
+ done : false ,
19
+ } ) ;
20
+ }
21
+ } , delay ) ;
22
+ }
23
+
24
+ [ Symbol . asyncIterator ] ( ) {
25
+ const next = ( ) => new Promise ( ( resolve ) => {
26
+ this . #resolve = resolve ;
27
+ } ) ;
28
+ const iterator = { next } ;
29
+ return iterator ;
30
+ }
31
+ }
32
+
33
+ // Usage
34
+
35
+ const main = async ( ) => {
36
+ const timer = new Timer ( 1000 ) ;
37
+
38
+ ( async ( ) => {
39
+ console . log ( 'Section 1 start' ) ;
40
+ for await ( const step of timer ) {
41
+ console . log ( { section : 1 , step } ) ;
42
+ }
43
+ } ) ( ) ;
44
+
45
+ ( async ( ) => {
46
+ console . log ( 'Section 2 start' ) ;
47
+ const iter = timer [ Symbol . asyncIterator ] ( ) ;
48
+ do {
49
+ const { value, done } = await iter . next ( ) ;
50
+ console . log ( { section : 2 , step : value , done } ) ;
51
+ } while ( true ) ;
52
+ } ) ( ) ;
53
+
54
+ ( async ( ) => {
55
+ console . log ( 'Section 3 start' ) ;
56
+ const iter = timer [ Symbol . asyncIterator ] ( ) ;
57
+ do {
58
+ const { value, done } = await iter . next ( ) ;
59
+ console . log ( { section : 3 , step : value , done } ) ;
60
+ } while ( true ) ;
61
+ } ) ( ) ;
62
+ } ;
63
+
64
+ main ( ) ;
You can’t perform that action at this time.
0 commit comments