Skip to content

Instantly share code, notes, and snippets.

@souenzzo
Last active July 1, 2021 02:12
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save souenzzo/ee4f1ef4124d21993e0c2e55d4626ce9 to your computer and use it in GitHub Desktop.
Save souenzzo/ee4f1ef4124d21993e0c2e55d4626ce9 to your computer and use it in GitHub Desktop.

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment