Skip to content

Instantly share code, notes, and snippets.

Last active Jul 1, 2021
What would you like to do?

How to turn your sync API into an async one

Let's suppose that you have a sync API send

(send params)

This API has at least 2 behaviors:

  1. Return a value
  2. Throw an exception

Minimal ex-handler

In our first atempt, we will add 1 extra parameter

(send-async params ex-handler)

This function now can:

  1. Thow a sync exception (before go async)
  2. Return a value, that is a promise
  3. Call ex-handler with the async exception. The return of ex-handler will be delivered into the promise
  4. Close the channel, even if ex-handler returns nil (that can't be inserted on a chan)

Good pratice

Is a core.async good pratice to allow the caller to pass it's return the channel

(send-async params ch ex-handler)

This function should still return ch

Full example

Sometimes the caller want full control over the channel, so you should allow the caller to control if you should close the channel or not.

(send-async params ch close? ex-handler)

Let's recap

  • send-async can throw before go async
  • ch is a optinal parameter, will always be returned by the function. On success, the result will be inserted and the channel closed.
  • close? will control if the channel will be closed or not
  • ex-handler is a function that receives an exception and returns a value. if it's value is not nil, it should be inserted on ch

This comment has been minimized.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment