如何在Kotlin中写下一系列承诺



是否可以只使用Kotlin编写一系列承诺(或任务(?

例如,JavaScript中的一个序列promise被写成:

const SLEEP_INTERVAL_IN_MILLISECONDS = 200;
const alpha = function alpha (number) {
return new Promise(function (resolve, reject) {
const fulfill = function() {
return resolve(number + 1);
};
return setTimeout(fulfill, SLEEP_INTERVAL_IN_MILLISECONDS);
});
};
const bravo = function bravo (number) {
return new Promise(function (resolve, reject) {
const fulfill = function() {
return resolve(Math.ceil(1000*Math.random()) + number);
};
return setTimeout(fulfill, SLEEP_INTERVAL_IN_MILLISECONDS);
});
};
const charlie = function charlie (number) {
return new Promise(function (resolve, reject) {
return (number%2 == 0) ? reject(number) : resolve(number);
});
};
function run() {
return Promise.resolve(42)
.then(alpha)
.then(bravo)
.then(charlie)
.then((number) => {
console.log('success: ' + number)
})
.catch((error) => {
console.log('error: ' + error);
});
}
run();

每个函数还返回一个具有异步处理结果的Promise,该结果将由紧接着的Promise解析/拒绝。

我知道如何使用RxKotlin来写这篇文章,但我正试图弄清楚如何使用协程库或任何其他标准功能来写它。

正如您所提到的,协同程序是标准的特性。

如果函数将被挂起,例如IO,或者如果调用另一个suspend函数,例如delay,则必须使用suspend关键字。

错误处理可以使用普通的try-catch语句来完成。

import kotlinx.coroutines.delay
import java.lang.Exception
import kotlin.math.ceil
const val SLEEP_INTERVAL_IN_MILLISECONDS = 200
suspend fun alpha(number: Int): Int {
delay(SLEEP_INTERVAL_IN_MILLISECONDS)
return number + 1
}
suspend fun bravo(number: Int): Int {
delay(SLEEP_INTERVAL_IN_MILLISECONDS)
return ceil(1000 * Math.random() + number).toInt()
}
fun charlie(number: Int): Int =
number.takeIf { it % 2 == 0 } ?: throw IllegalStateException(number.toString())
suspend fun run() {
try {
val result = charlie(bravo(alpha(42)))
println(result)
} catch (e: Exception) {
println(e)
}
}
suspend fun main() {
run()
}

如果你喜欢更实用的错误处理风格,你可以这样做:

suspend fun run() {
runCatching { charlie(bravo(alpha(42))) }
.onFailure { println(it) }
.onSuccess { println(it) }
}

最新更新