Monday, June 29, 2020

Converting between coroutines and promises in Kotlin JS

Most modern JavaScript libraries handle asynchronicity by passing around "promise" objects that can be chained together to make a workflow with several suspension points. These are perfectly usable in Kotlin JS, but it would be even nicer if Kotlin's excellent support and cleaner syntax for coroutines and suspending functions could be used.

In a coroutine, a promise can be awaited (i.e. its behavior called in a suspending manner) with its await() extension function, which suspends. A coroutine context can be turned into a promise object by putting the suspending code inside a GlobalScope.promise block (or that of any other CoroutineScope). Such promises can be used by plain JavaScript code.

No comments:

Post a Comment