# What is the execution order of suspended functions?

**URL:** <https://discuss.kotlinlang.org/t/what-is-the-execution-order-of-suspended-functions/25984>\
**Category:** Libraries\
**Created:** [November 21, 2022, 5:53pm UTC](https://discuss.kotlinlang.org/t/what-is-the-execution-order-of-suspended-functions/25984 "2022-11-21T17:53:21Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![fedorov1984](https://avatars.discourse-cdn.com/v4/letter/f/c0e974/32.png) [@fedorov1984](https://discuss.kotlinlang.org/u/fedorov1984)\
**Post date:** [November 21, 2022, 5:53pm UTC](https://discuss.kotlinlang.org/t/what-is-the-execution-order-of-suspended-functions/25984/1 "2022-11-21T17:53:21Z")

</div>

I am puzzled by how code with coroutines is executed:

```auto
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking

fun main() {
    runBlocking {
        launch {
            println("main:Do A")
            doA()
            println("main:A is done")
            println("main:Do B")
            doB()
            println("main:B is done")
        }
    }
}

suspend fun doB() {
    println("suspended:Doing A")
    delay(1000)
}

suspend fun doA() {
    println("suspended:Doing B")
    delay(1000)
}

```

Output:

```auto
main:Do A
suspended:Doing B
main:A is done
main:Do B
suspended:Doing A
main:B is done

```

The order or invocations is very confusing. How is it possible that after `main:Do A` we jump right into second suspend function. Is there a way to see how this code is transformed, or would look like in java?

---

<div class="post-metadata">

**Author:** ![kyay10](https://avatars.discourse-cdn.com/v4/letter/k/c57346/32.png) [@kyay10](https://discuss.kotlinlang.org/u/kyay10)\
**Post date:** [November 21, 2022, 6:28pm UTC](https://discuss.kotlinlang.org/t/what-is-the-execution-order-of-suspended-functions/25984/2 "2022-11-21T18:28:28Z")

</div>

```run-kotlin
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking

fun main() {
    runBlocking {
        launch {
            println("main:Do A")
            doA()
            println("main:A is done")
            println("main:Do B")
            doB()
            println("main:B is done")
        }
    }
}

suspend fun doA() {
    println("suspended:Doing A")
    delay(1000)
}

suspend fun doB() {
    println("suspended:Doing B")
    delay(1000)
}

```

You’ve got your functions named the wrong way around (or equivalently, you’ve got the `println("suspended:Doing X")` the wrong way around), that’s all 😃

---

<div class="post-metadata">

**Author:** ![fedorov1984](https://avatars.discourse-cdn.com/v4/letter/f/c0e974/32.png) [@fedorov1984](https://discuss.kotlinlang.org/u/fedorov1984)\
**Post date:** [November 21, 2022, 6:48pm UTC](https://discuss.kotlinlang.org/t/what-is-the-execution-order-of-suspended-functions/25984/3 "2022-11-21T18:48:16Z")

</div>

cool story, insane!
