D
Deno

help

How to stop reading from a ReadableStream?

R!Roricchi 2.0『藤田の妻』11/13/2022
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
Jjeff.hykin11/24/2022
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.

Looking for more? Join the community!