Skip to content

Instantly share code, notes, and snippets.

@mceachen
Created July 11, 2020 21:14
Show Gist options
  • Save mceachen/52a9ae7b51c247d5d02d38727d1f0101 to your computer and use it in GitHub Desktop.
Save mceachen/52a9ae7b51c247d5d02d38727d1f0101 to your computer and use it in GitHub Desktop.

Revisions

  1. mceachen created this gist Jul 11, 2020.
    23 changes: 23 additions & 0 deletions thenCollect.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,23 @@
    export type SyncOrAsync<T> = T | Promise<T>
    export type Maybe<T> = T | undefined
    export type MaybeSyncOrAsync<T> = Maybe<SyncOrAsync<Maybe<T>>>

    /**
    * Serialized promise gathering and compaction
    */
    export async function thenCollect<T1, T2>(
    arr: MaybeSyncOrAsync<MaybeSyncOrAsync<T1>[]>,
    f: (t: T1) => MaybeSyncOrAsync<T2>
    ): Promise<T2[]> {
    const result: T2[] = []
    for (const eaP of toA(await arr)) {
    if (eaP != null) {
    const ea = await eaP
    if (ea != null) {
    const r = await f(ea)
    if (r != null) result.push(r)
    }
    }
    }
    return result
    }