加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 以异步方式返回Future的更好方法

发布时间:2020-12-16 18:10:00 所属栏目:安全 来源:网络整理
导读:def fun = { val a = Future {println("Inside Future"); throw new Exception("Discomfort in the sea has pulled itself upon me"); 5} a onComplete {_ = Thread.sleep(5000); println("Inside map") } a} 上面是一个非常简单的片段.返回类型是Future.如
def fun = {
  val a = Future {println("Inside Future"); throw new Exception("Discomfort in the sea has pulled itself upon me"); 5}
  a onComplete {_ => Thread.sleep(5000); println("Inside map") }
  a
}

上面是一个非常简单的片段.返回类型是Future.如果没有将Future的值存储在val中并且仍然具有onComplete但仍然能够返回Future,是否有更好的方法?

解决方法

andThen可以帮助解决副作用.请注意,即使抛出异常,也会忽略对andThen调用内返回的值.

def fun = {
  Future {println("Inside Future"); throw new Exception("Discomfort in the sea has pulled itself upon me"); 5}
    .andThen {case _ => Thread.sleep(5000); println("Inside map") }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读