Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: it-foreach should only await thenables #100

Merged
merged 1 commit into from
Nov 12, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 18 additions & 4 deletions packages/it-foreach/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ function isAsyncIterable <T> (thing: any): thing is AsyncIterable<T> {
return thing[Symbol.asyncIterator] != null
}

function isPromise <T = unknown> (thing: any): thing is Promise<T> {
return thing?.then != null
}

/**
* Invokes the passed function for each item in an iterable
*/
Expand All @@ -13,9 +17,14 @@ function forEach <T> (source: Iterable<T> | AsyncIterable<T>, fn: (thing: T) =>
function forEach <T> (source: Iterable<T> | AsyncIterable<T>, fn: (thing: T) => void | Promise<void>): AsyncGenerator<T, void, undefined> | Generator<T, void, undefined> {
if (isAsyncIterable(source)) {
return (async function * () {
for await (const thing of source) {
await fn(thing)
yield thing
for await (const val of source) {
const res = fn(val)

if (isPromise(res)) {
await res
}

yield val
}
})()
}
Expand All @@ -35,7 +44,12 @@ function forEach <T> (source: Iterable<T> | AsyncIterable<T>, fn: (thing: T) =>
yield value

for await (const val of peekable) {
await fn(val)
const res = fn(val)

if (isPromise(res)) {
await res
}

yield val
}
})()
Expand Down
Loading