Site icon The Winter Blog

Callbacks Vs JavaScript promises & Kotlin coroutines

Convert callback based asynchronous methods for more linear code, with Promises + Async/Await in JavaScript and Coroutines in Kotlin.

In JavaScript, wrap the callback based method inside a new Promise((resolve, reject) => {...}) call. Then call the resolve/reject method of the promise on callback completion. The result is an asynchronous promise that resolves with the result of the callback.

In Kotlin, wrap the callback based method inside a suspendCoroutine {continuation-> ...}. Then call continuation.resume or continuation.resumeWithException on callback completion. The result is an asynchronous/suspending Coroutine that returns the value of the callback.

A small drawback of these approaches is that they return a single value, while the callback can have multiple values. The solution to this is to wrap the values returned from the callback in an object (JS) or data class (Kotlin).

Exit mobile version