Skip to content

Instantly share code, notes, and snippets.

@mcollina
Last active May 19, 2021 21:48
merge ensuring that all generators are fully consumed
import { setTimeout } from 'timers/promises'
import { strictEqual } from 'assert'
let called = 0
async function * merge (a, b) {
try {
yield *a
yield *b
} finally {
// Ensure that the two iterators are fully consumed
// in case of streams, you might want to
// destroy the stream itself.
for await (const _ of a) {}
for await (const _ of b) {}
}
}
async function * funA (str) {
try {
yield str + 1
await setTimeout(1000)
yield str + 2
await setTimeout(1000)
yield str + 3
await setTimeout(1000)
yield str + 4
} finally {
called++
console.log('finally', str)
}
}
for await (const chunk of merge(funA('a'), funA('b'))) {
console.log(chunk)
// Comment the following line to see the difference
if (chunk == 'a2') break
}
strictEqual(called, 2)
import { setTimeout } from 'timers/promises'
import { strictEqual } from 'assert'
let called = 0
async function * merge (a, b) {
yield *a
yield *b
}
async function * funA (str) {
try {
yield str + 1
await setTimeout(1000)
yield str + 2
await setTimeout(1000)
yield str + 3
await setTimeout(1000)
yield str + 4
} finally {
called++
console.log('finally', str)
}
}
for await (const chunk of merge(funA('a'), funA('b'))) {
console.log(chunk)
// Comment the following line to see the difference
if (chunk == 'a2') break
}
strictEqual(called, 2)
import { setTimeout } from 'timers/promises'
import { strictEqual } from 'assert'
let called = 0
async function * merge (a, b) {
try {
yield *a
yield *b
} finally {
const settled = await Promise.allSettled([
a.next(),
b.next(),
a.return(),
b.return()
])
// For debugging purposes only
console.log(settled)
}
}
async function * funA (str) {
try {
yield str + 1
await setTimeout(1000)
yield str + 2
await setTimeout(1000)
yield str + 3
await setTimeout(1000)
yield str + 4
} finally {
called++
console.log('finally', str)
}
}
for await (const chunk of merge(funA('a'), funA('b'))) {
console.log(chunk)
// Comment the following line to see the difference
if (chunk == 'a2') break
}
strictEqual(called, 2)
import { setTimeout } from 'timers/promises'
import { strictEqual } from 'assert'
let called = 0
async function * merge (a, b) {
try {
yield *a
yield *b
} finally {
const settled = await Promise.allSettled([
a.next(),
b.next(),
a.throw(new Error('kaboom a')),
b.throw(new Error('kaboom b'))
])
// For debugging purposes only
console.log(settled)
}
}
async function * funA (str) {
try {
yield str + 1
await setTimeout(1000)
yield str + 2
await setTimeout(1000)
yield str + 3
await setTimeout(1000)
yield str + 4
} finally {
called++
console.log('finally', str)
}
}
for await (const chunk of merge(funA('a'), funA('b'))) {
console.log(chunk)
// Comment the following line to see the difference
if (chunk == 'a2') break
}
strictEqual(called, 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment