首页 > 编程语言 >【Coroutines】Implement JavaScript Promise by Kotlin Coroutine

【Coroutines】Implement JavaScript Promise by Kotlin Coroutine

时间:2024-10-21 21:17:49浏览次数:3  
标签:await Coroutine Kotlin JavaScript println Promise continuation fun async

Expected

use async to launch a async task

use await to wait result from other work

async {
    val user = await<String> { loadUserInfo() }
    println(user)
    println("async returned")
}
println("async not return")
Implementation

async can implemented with startCoroutine

await can implemented with suspendCoroutine

package com.code.kotlin

import kotlin.coroutines.*

interface Promise<T> {
    fun resume(value: T)
    fun error(e: Throwable)
}

internal class PromiseImpl<T> : Promise<T>, Continuation<Unit> {

    override val context = EmptyCoroutineContext

    internal lateinit var continuation: Continuation<T>

    override fun resumeWith(result: Result<Unit>) {
        result.getOrThrow()
    }

    override fun resume(value: T) {
        continuation.resume(value)
    }

    override fun error(e: Throwable) {
        continuation.resumeWithException(e)
    }
}

fun <T> async(
    block: suspend Promise<T>.() -> Unit
): Promise<T> {
    val promise = PromiseImpl<T>()
    block.startCoroutine(promise, promise)
    return promise
}

suspend fun <T> Promise<T>.await(
    block: Promise<T>.() -> Unit
) = suspendCoroutine { continuation ->
    val impl = this as PromiseImpl<T>
    impl.continuation = continuation
    impl.block()
}
package com.code.kotlin

import kotlin.concurrent.thread

fun main() {
    async {
        val user = await<String> { loadUserInfo() }
        println(user)
        println("async returned")
    }
    println("async not return")
}

fun Promise<String>.loadUserInfo() {
    thread {
        Thread.sleep(3000L)
        try {
            resume("Darius")
        } catch (e: Throwable) {
            error(e)
        }
    }
}

await can wait result from both blocking code / async code / suspend code, only resume is called

标签:await,Coroutine,Kotlin,JavaScript,println,Promise,continuation,fun,async
From: https://blog.csdn.net/u013718730/article/details/143105006

相关文章

  • [Javascript] Write memoize function
    classMemoizeMap{constructor(){this._map=newMap();this._weakMap=newWeakMap();}_isObject(v){returntypeofv==="object"&&v!==null;}set(key,value){if(this._isObject(key)){this._......
  • JavaScriptBOM操作
    认识BOM操作◼BOM:浏览器对象模型(BrowserObjectModel)简称BOM,由浏览器提供的用于处理文档(document)之外的所有内容的其他对象;比如navigator、location、history等对象;◼JavaScript有一个非常重要的运行环境就是浏览器而且浏览器本身又作为一个应用程序需要对其......
  • JavaScript的DOM操作
    元素的继承classStudentextendsPerson{}创建一个Student对象继承自Person对象本身会自带Person的属性并且可以创建属于自己的属性什么是DOM?◼前面我们花了很多时间学习JavaScript的基本语法,但是这些基本语法,但是这些语法好像和做网页没有什么关系,和前面学习的H......
  • JavaScript的事件处理
    认识事件处理◼Web页面需要经常和用户之间进行交互,而交互的过程中我们可能想要捕捉这个交互的过程:比如用户点击了某个按钮、用户在输入框里面输入了某个文本、用户鼠标经过了某个位置;浏览器需要搭建一条JavaScript代码和事件之间的桥梁;当某个事件发生时,让JavaScr......
  • JavaScript递归按条件过滤掉子级数据
    有一个子父级树形结构的数据,现需要递归遍历,找到类型为‘1’的数据,过滤子级,最后返回树形结构数据代码如下//调用方法,返回按要求过滤后的数据constnewArr=this.clearChildrenOfTypeIndex(arr)//定义过滤方法clearChildrenOfTypeIndex(tree){//避免原始数组被直接修改......
  • 使用 JavaScript (Node.js) 实现验证码识别与自动化登录
    安装所需依赖首先,确保你已经安装了Node.js。然后,使用npm安装所需的库:bashnpminstallaxiosjimptesseract.js2.下载验证码图片使用axios下载验证码图片并保存到本地:更多内容联系1436423940javascriptconstfs=require('fs');constaxios=require('axios');......
  • WebRTC JavaScript API使用和介绍
    目录API列表API列表WebRTCJavaScriptAPI是WebReal-TimeCommunication(WebRTC)技术的核心,它允许网页应用实现浏览器间的实时音频、视频通信及数据共享,无需依赖插件。navigator.mediaDevices.getUserMedia()作用:请求访问用户的媒体设备(如摄像头和麦克风)。代码示例......
  • JavaScript事件循环:一杯咖啡的时间,搞懂主线程都经历了什么?
    我们今天来聊聊JavaScript事件循环。虽然这个词听起来很高深,但你可以把它想象成一个奶茶店里排队买奶茶的过程。主线程就像奶茶店的唯一一个店员,任务就是那些排队的订单,而JavaScript的事件循环就是这个店员处理订单的工作方式。先看代码,咱们慢慢聊:console.log('1:进店......
  • JavaScript 的基础语法和数据类型的概述
    JavaScript是一种广泛使用的编程语言,主要用于Web开发。它拥有简洁的语法和丰富的功能。以下是JavaScript的基础语法和数据类型的概述。基础语法变量声明使用var、let或const关键字声明变量。varname="Alice";letage=25;constpi=3.14;数据类型J......
  • javascript输出金字塔
    <script>//首先创造一个空的变量letstr=''letlevel=prompt("输入金字塔的层数")//获取输入的纯数字,其余情况都转化为NaNlevel=parseInt(level)&&Number(level)//判断用户的输入是否合法if(isNaN(level)){alert("金字塔的数......