gpt4 book ai didi

scala - 如何使用 scala.js 读取文本文件?

转载 作者:行者123 更新时间:2023-12-02 08:27:54 25 4
gpt4 key购买 nike

基本上我想弄清楚我需要传递给 onload() 方法的内容

def selectedFile(e: ReactEventI) = {
val reader = new dom.FileReader()
reader.readAsText(e.currentTarget.files.item(0))
reader.onload(
)
}

最佳答案

惯用的 Scala,带有错误处理

我更喜欢使用模式匹配和 map,而不是使用回调:

def printFileContent(file: dom.File) =
readTextFile(file).map {
case Right(fileContent) => println(s"File content: $fileContent")
case Left(error) => println(s"Could not read file ${file.name}. Error: $error")
}

代码:

/** In the future, returns either the file's content or an error,
if something went wrong */
def readTextFile(fileToRead: dom.File): Future[Either[DOMError, String]] = {

// Used to create the Future containing either the file content or an error
val promisedErrorOrContent = Promise[Either[DOMError, String]]

val reader = new FileReader()
reader.readAsText(fileToRead, "UTF-8")

reader.onload = (_: UIEvent) => {
val resultAsString = s"${reader.result}"
promisedErrorOrContent.success(Right(resultAsString))
}
reader.onerror = (_: Event) => promisedErrorOrContent.success(Left(reader.error))

promisedErrorOrContent.future
}

关于scala - 如何使用 scala.js 读取文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30332326/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com