How to stop reading from a ReadableStream?

let user

for await (const data of readable) {
if (data.user.id === 'user-id') {
user = data

break
}
}

console.log(user)
let user

for await (const data of readable) {
if (data.user.id === 'user-id') {
user = data

break
}
}

console.log(user)
the break stops the for loop, but it doesnt exit? because it only logs the user after the readable stream is completed. i dont want to wait for the stream to complete/end, i want to get user immidiately after break is called. here readable is ReadableStream
1 Reply
jeff.hykin
jeff.hykin2y ago
In this case you probably need to do manual iteration instead of using a for-of loop. See an example here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators I imagine it'll be like the following but with some await's
const it = makeRangeIterator(1, 10, 2);

let result = it.next();
while (!result.done) {
console.log(result.value); // 1 3 5 7 9
result = it.next();
}

console.log("Iterated over sequence of size: ", result.value); // [5 numbers returned, that took interval in between: 0 to 10]
const it = makeRangeIterator(1, 10, 2);

let result = it.next();
while (!result.done) {
console.log(result.value); // 1 3 5 7 9
result = it.next();
}

console.log("Iterated over sequence of size: ", result.value); // [5 numbers returned, that took interval in between: 0 to 10]
Iterators and generators - JavaScript | MDN
Iterators and Generators bring the concept of iteration directly into the core language and provide a mechanism for customizing the behavior of for...of loops.