我如何在Kotlin中编写承诺序列?

我如何在Kotlin中编写承诺序列?,第1张

概述是否可以仅使用Kotlin编写promise(或任务)的序列?例如,JavaScript中的promise序列写为:constSLEEP_INTERVAL_IN_MILLISECONDS=200;constalpha=functionalpha(number){returnnewPromise(function(resolve,reject){constfulfill=function(){

是否可以仅使用Kotlin编写promise(或任务)的序列?

例如,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();

每个具有异步处理结果的功能also returns a Promise,都将由紧随其后的承诺来解决/拒绝.

我知道如何使用RxKotlin编写此代码,但我试图弄清楚如何使用coroutines library或任何其他标准功能编写它.

解决方法:

正如您提到的,coroutines是要使用的标准功能.

如果函数将被挂起,则必须使用suspend关键字,例如IO,或者如果您调用其他暂停函数,例如延迟.

错误处理可以通过普通的try-catch语句完成.

import kotlinx.coroutines.delayimport java.lang.Exceptionimport kotlin.math.ceilconst val SLEEP_INTERVAL_IN_MILliSECONDS = 200suspend 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) }}
总结

以上是内存溢出为你收集整理的我如何在Kotlin中编写承诺序列?全部内容,希望文章能够帮你解决我如何在Kotlin中编写承诺序列?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1082013.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-27
下一篇 2022-05-27

发表评论

登录后才能评论

评论列表(0条)

保存