【发布时间】:2020-02-23 03:44:01
【问题描述】:
我正在尝试为 request 库编写一个 Scalajs 外观,它有一个使用回调模式的方法:
request('http://www.google.com', function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print the HTML for the Google homepage.
});
在此模式中,error 为 null,response 和 body 已定义,反之亦然。
在 ScalaJS 外观中反映这种模式的最佳方式是什么?我能想到的最好的方法是:
@js.native
@JSImport("request", JSImport.Default)
object Request extends js.Object {
def apply[A](uri: String,
requestConfig: js.Object,
callback: js.Function2[js.JavaScriptException, Response, A]): Unit = js.native
}
执行该方法后,我使用Option 匹配正确的大小写:
Request(url, RequestConfig(queryString, headers), (error, response) => {
(Option(error), Option(response)) match {
case (Some(err), _) => // handle error
case (_, Some(res)) => // handle success
case (None, None) => // This will only happen if there is a bug in the request library
}
})
我不喜欢这样,因为 1) 我必须为 (None, None) 编写一个不必要的匹配项,或者忽略非详尽的匹配警告,以及 2) 外观没有准确地描述类型。
我也尝试过使用js.UndefOr[js.JavaScriptException],但这会从.toOption 和js.JavaScriptException | Null 返回Some(null),但我似乎只能将其转换为Option[js.JavaScriptException | Null]。
【问题讨论】:
-
也许将您的包装输入为
Either[JavaScriptException, Response]?另外,我不知道 Scala.js 中Future的状态,但如果可能,我会尽量避免回调并执行def apply(uri, config): Future[Response],如果出现异常,Future 将失败。然后变成Request(uri, config).map(response => turnIntoA)
标签: scala.js