=================
== The Archive ==
=================

[Elixir] Task (async, await)

|

AI Summary

  • Elixir의 Task 모듈을 사용해 async와 await 기능을 다양한 예제로 소개한다.
  • Task.async_stream은 스트림의 각 요소를 비동기 처리하고 결과를 순차적으로 합산하는 데 사용된다.
  • Task.async_streamStream.take를 조합해 일부 요소만 비동기로 처리하고 결과를 리스트로 변환할 수 있다.
  • Task.async로 비동기 작업을 생성하고 Task.await로 결과를 기다려 합산 결과를 얻는 예시가 있다.
  • 여러 비동기 작업을 리스트로 만들고 Task.await_many로 한꺼번에 결과를 받을 수 있다.
  • 공식 문서와 예제 코드는 참고 링크를 통해 확인할 수 있다.
Updated: 2025-11-22 15:36 UTC

Introduction

async_stream

1
2
3
4
5
stream =
  ["long string", "longer string", "there are many of these"]
  |> Task.async_stream(fn text -> text |> String.codepoints() |> Enum.count() end)

assert Enum.reduce(stream, 0, fn {:ok, num}, acc -> num + acc end) == 47

unbound async + take

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
result =
  1..100
  |> Stream.take(10)
  |> Task.async_stream(fn i ->
    Process.sleep(100)
    i
  end)
  |> Enum.map(fn {:ok, val} -> val end)
  |> Enum.to_list()

assert result == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

async / await

1
2
task = Task.async(fn -> Enum.sum(0..999_999) end)
assert Task.await(task) == 499_999_500_000

await_many

1
2
3
4
5
6
tasks = [
  Task.async(fn -> 1 + 1 end),
  Task.async(fn -> 2 + 3 end)
]

assert Task.await_many(tasks) == [2, 5]

References

Categories:

Tags: