August 21, 2021

Inside Out Async

I nerdsniped myself and made a handy async utility that turns Promises and AsyncGenerators inside out. This is very handy for testing and useful if you're done non trivial transformations of events into async generator or promised based apis. I call it Inside Out Async.

My development journey was posted in realtime and preserved below.

Francis 🏴‍☠️ Gulotta icon

Francis 🏴‍☠️ Gulotta

@reconbot

Posted on August 08, 2021

export function defer<T>(): IDeferred<T> {
  let reject
  let resolve
  const promise = new Promise<T>((resolveFunc, rejectFunc) => {
    resolve = resolveFunc
    reject = rejectFunc
  })
  return {
    promise,
    reject,
    resolve,
  }
}

export interface IDeferred<T> {
  promise: Promise<T>
  resolve: (value: T) => void
  reject: (error: Error) => void
}
Francis 🏴‍☠️ Gulotta icon

Francis 🏴‍☠️ Gulotta

@reconbot

Posted on August 08, 2021

Francis 🏴‍☠️ Gulotta icon

Francis 🏴‍☠️ Gulotta

@reconbot

Posted on August 09, 2021

Francis 🏴‍☠️ Gulotta icon

Francis 🏴‍☠️ Gulotta

@reconbot

Posted on August 09, 2021

Francis 🏴‍☠️ Gulotta icon

Francis 🏴‍☠️ Gulotta

@reconbot

Posted on August 09, 2021

Francis 🏴‍☠️ Gulotta icon

Francis 🏴‍☠️ Gulotta

@reconbot

Posted on August 09, 2021

  it('queues up values until queueError is called', async () => {
    const deferred = deferGenerator<number, undefined>()
    deferred.queueValue(1)
    deferred.queueValue(2)
    deferred.queueValue(3)
    deferred.queueError(new Error('oh no!'))
    const values: number[] = []
    try {
      for await (const val of deferred.generator) {
        values.push(val)
      }
      throw new Error('should have errored')
    } catch (e) {
      assert.equal(e.message, 'oh no!')
    }
    assert.deepEqual(values, [1, 2, 3])
  })
Francis 🏴‍☠️ Gulotta icon

Francis 🏴‍☠️ Gulotta

@reconbot

Posted on August 09, 2021

Francis 🏴‍☠️ Gulotta icon

Francis 🏴‍☠️ Gulotta

@reconbot

Posted on August 09, 2021

Francis 🏴‍☠️ Gulotta icon

Francis 🏴‍☠️ Gulotta

@reconbot

Posted on August 10, 2021


const executeSubscription = async (query: string) => {
  const client = createClient({
    url: 'ws://localhost:3339',
    webSocketImpl: WebSocket,
  })

  const values = deferGenerator()

  const unsubscribe = client.subscribe(
    { query },
    {
      next: ({data}) => {
        values.queueValue(data)
      },
      error: (error: Error) => {
        values.queueError(error)
      },
      complete: () => values.queueReturn(),
    },
  )

  return { values: values.generator, unsubscribe }
}
Roborooter.com © 2024
Powered by ⚡️ and 🤖.