Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. Kotlin Dictionary
  3. await() / Deferred

await() / Deferred

In Kotlin coroutines, Deferred<T> is an object that holds the result of an asynchronous operation. Calling await() on it suspends the current coroutine until the result is ready.

Syntax

// Get a Deferred using async
val deferred: Deferred<Type> = async {
    // Asynchronous operation
    result  // Return value
}

// Get the result with await (can only be called inside a coroutine)
val result: Type = deferred.await()

// Use awaitAll to wait for multiple Deferreds at once
val results: List<Type> = awaitAll(deferred1, deferred2, deferred3)

Methods and Properties

Method / PropertyDescription
deferred.await()Suspends the coroutine until the result is ready, then returns it.
awaitAll(vararg deferred)Waits for multiple Deferreds concurrently and returns a list of results.
deferred.isCompletedReturns whether the operation has completed.
deferred.isCancelledReturns whether the operation has been cancelled.
deferred.cancel()Cancels the asynchronous operation.
deferred.getCompleted()Returns the result if completed; throws an exception if not yet complete.

Sample Code

import kotlinx.coroutines.*

suspend fun fetchUser(id: Int): String {
    delay(200)
    return "User-$id"
}

suspend fun fetchScore(id: Int): Int {
    delay(150)
    return id * 100
}

fun main() = runBlocking {
    // Launch two async operations concurrently.
    val userDeferred = async { fetchUser(1) }
    val scoreDeferred = async { fetchScore(1) }

    // Retrieve each result using await.
    val user = userDeferred.await()
    val score = scoreDeferred.await()
    println("$user: $score points")  // User-1: 100 points

    // Use awaitAll to retrieve multiple results at once.
    val deferreds = (1..3).map { id ->
        async { fetchUser(id) }
    }
    val users = awaitAll(*deferreds.toTypedArray())
    println(users)  // [User-1, User-2, User-3]

    // Check completion with isCompleted
    val d = async { delay(500); "done" }
    println(d.isCompleted)  // false (still running)
    d.await()
    println(d.isCompleted)  // true
}

Notes

To run operations in parallel, launch multiple async blocks first and then call await() on each afterward. Calling await() immediately after each async results in sequential execution.

Use awaitAll() to wait for multiple Deferreds together. If any one of them throws an exception, the others are cancelled as well.

For details on how to launch coroutines, see launch / async. For timeouts, see delay() / withTimeout().

If you find any errors or copyright issues, please .