Skip to content

Instantly share code, notes, and snippets.

@namelos
Last active May 1, 2018 01:20
Show Gist options
  • Save namelos/e34c22c705fa4460a2768cd64e930dbe to your computer and use it in GitHub Desktop.
Save namelos/e34c22c705fa4460a2768cd64e930dbe to your computer and use it in GitHub Desktop.
Generic task
defmodule GenTask do
def async do
parent = self()
spawn(fn ->
receive do
{:resolve, value} -> send parent, {self(), :result, value}
{:reject, reason} -> send parent, {self(), :reject, reason}
end
end)
end
def resolve(pid, value) do
send pid, {:resolve, value}
end
def reject(pid, reason) do
send pid, {:reject, reason}
end
def await(pid) do
receive do
{^pid, :result, value} -> {:ok, value}
{^pid, :reject, reason} -> {:error, reason}
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment