# Using coroutines to avoid callback hell when using XMLHttpRequest

**URL:** <https://discuss.kotlinlang.org/t/using-coroutines-to-avoid-callback-hell-when-using-xmlhttprequest/2450>\
**Category:** JavaScript\
**Created:** [March 29, 2017, 5:36pm UTC](https://discuss.kotlinlang.org/t/using-coroutines-to-avoid-callback-hell-when-using-xmlhttprequest/2450 "2017-03-29T17:36:21Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

**Author:** ![Alexey.Andreev](https://avatars.discourse-cdn.com/v4/letter/a/e36b37/32.png) [@Alexey.Andreev](https://discuss.kotlinlang.org/u/Alexey.Andreev)\
**Post date:** [March 30, 2017, 9:33am UTC](https://discuss.kotlinlang.org/t/using-coroutines-to-avoid-callback-hell-when-using-xmlhttprequest/2450/3 "2017-03-30T09:33:22Z")

</div>

> I’ve been experiencing with some code from a previous post and the docs… but feel a bit unsure whether I’m on the right track.

The code you provided looks fine. Did you try it? Are there any problems?

> Are Kotlin coroutines for Javascript ready enough to replace javascript promises?

No, they are even not meant to. Kotlin coroutines are not replacement for promises, but enhancement. You can write a similar coroutine for promises, so you’ll be able to easily create and use promises.

Here’s an example:

```auto
public fun <T> async(c: suspend () -> T): Promise<T> {
    return Promise { resolve, reject ->
        c.startCoroutine(object : Continuation<T> {
            override fun resume(value: T) = resolve(value)

            override fun resumeWithException(exception: Throwable) = reject(exception)

            override val context = EmptyCoroutineContext
        })
    }
}

public suspend fun <T> Promise<T>.await() = suspendCoroutine<T> { c ->
    then({ c.resume(it) }, { c.resumeWithException(it) })
}

```

---

_[View the full topic](https://discuss.kotlinlang.org/t/using-coroutines-to-avoid-callback-hell-when-using-xmlhttprequest/2450)._
