Skip to content

Instantly share code, notes, and snippets.

@soriyath
Last active February 14, 2017 01:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soriyath/13e66361c5d4c9b4f593f2058663dc6a to your computer and use it in GitHub Desktop.
Save soriyath/13e66361c5d4c9b4f593f2058663dc6a to your computer and use it in GitHub Desktop.
How to return value from Task.async?
defmodule Test do
@doc ~S"""
iex> Test.download("http://www.six-swiss-exchange.com/data/market/statistics/corrections_2017-02-03.csv", "test.csv")
"""
def download(src, output_filename) do
Logger.info "Downloading #{src} -> #{output_filename}"
Task.async(getURL(src))
|> Task.await
|> Task.async(&(fn -> File.write!(output_filename, &1) end))
|> Task.await
Logger.info("Done Downloading #{src} -> #{output_filename}")
end
defp getURL(src) do
case HTTPoison.get(src) do
{:ok, response} -> response.body
{:error, error} -> (
Logger.error "could not download file. #{error.id} - #{error.reason}"
:error
)
end
end
end
@elbow-jason
Copy link

elbow-jason commented Feb 6, 2017

def download(src, output_filename) do
    Logger.info "Downloading #{src} -> #{output_filename}"
    Task.async(fn -> getURL(src) end)
    |> Task.await
    |> Task.async(&(fn -> File.write!(output_filename, &1) end))
    |> Task.await
    |> IO.puts
    Logger.info("Done Downloading #{src} -> #{output_filename}")
  end

  defp getURL(src) do 
    case HTTPoison.get(src) do
      {:ok, response} -> {:ok, response.body}
      {:error, error} -> (
        Logger.error "could not download file. #{error.id} - #{error.reason}"
        :error
      )
    end
  end

@dimitarvp
Copy link

@soriyath Could you explain your exact goal in this gist?

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