3
3
const {
4
4
PromisePrototypeThen,
5
5
SymbolAsyncIterator,
6
- SymbolIterator
6
+ SymbolIterator,
7
7
} = primordials ;
8
8
const { Buffer } = require ( 'buffer' ) ;
9
9
@@ -25,18 +25,22 @@ function from(Readable, iterable, opts) {
25
25
} ) ;
26
26
}
27
27
28
- if ( iterable && iterable [ SymbolAsyncIterator ] )
28
+ let isAsync = false ;
29
+ if ( iterable && iterable [ SymbolAsyncIterator ] ) {
30
+ isAsync = true ;
29
31
iterator = iterable [ SymbolAsyncIterator ] ( ) ;
30
- else if ( iterable && iterable [ SymbolIterator ] )
32
+ } else if ( iterable && iterable [ SymbolIterator ] ) {
33
+ isAsync = false ;
31
34
iterator = iterable [ SymbolIterator ] ( ) ;
32
- else
35
+ } else {
33
36
throw new ERR_INVALID_ARG_TYPE ( 'iterable' , [ 'Iterable' ] , iterable ) ;
37
+ }
34
38
35
39
const readable = new Readable ( {
36
40
objectMode : true ,
37
41
highWaterMark : 1 ,
38
42
// TODO(ronag): What options should be allowed?
39
- ...opts
43
+ ...opts ,
40
44
} ) ;
41
45
42
46
// Flag to protect against _read
@@ -75,23 +79,32 @@ function from(Readable, iterable, opts) {
75
79
}
76
80
77
81
async function next ( ) {
78
- try {
79
- const { value, done } = await iterator . next ( ) ;
80
- if ( done ) {
81
- readable . push ( null ) ;
82
- } else {
83
- const res = await value ;
84
- if ( res === null ) {
85
- reading = false ;
86
- throw new ERR_STREAM_NULL_VALUES ( ) ;
87
- } else if ( readable . push ( res ) ) {
88
- next ( ) ;
82
+ for ( ; ; ) {
83
+ try {
84
+ const { value, done } = isAsync ?
85
+ await iterator . next ( ) :
86
+ iterator . next ( ) ;
87
+
88
+ if ( done ) {
89
+ readable . push ( null ) ;
89
90
} else {
90
- reading = false ;
91
+ const res = ( value &&
92
+ typeof value . then === 'function' ) ?
93
+ await value :
94
+ value ;
95
+ if ( res === null ) {
96
+ reading = false ;
97
+ throw new ERR_STREAM_NULL_VALUES ( ) ;
98
+ } else if ( readable . push ( res ) ) {
99
+ continue ;
100
+ } else {
101
+ reading = false ;
102
+ }
91
103
}
104
+ } catch ( err ) {
105
+ readable . destroy ( err ) ;
92
106
}
93
- } catch ( err ) {
94
- readable . destroy ( err ) ;
107
+ break ;
95
108
}
96
109
}
97
110
return readable ;
0 commit comments