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

scala – 未来回调方法与Promises [成功与失败]之间的区别?

发布时间:2020-12-16 09:58:42 所属栏目:安全 来源:网络整理
导读:我使用Future和Promises来学习 Scala Concurrency. 我没有说明问题,使用Callback方法和使用Promise完成Future的确切区别是什么? 这是否意味着Future Callback方法实际上没有完成未来?只有使用Promise我们才能完成未来? 此外,我已经看到许多像你这样的地方
我使用Future和Promises来学习 Scala Concurrency.

我没有说明问题,使用Callback方法和使用Promise完成Future的确切区别是什么?

这是否意味着Future Callback方法实际上没有完成未来?只有使用Promise我们才能完成未来?

此外,我已经看到许多像你这样的地方可以阅读期货和承诺,但你只能写信给Promises.

解决方法

期货只在异步计算结束时完成:

val f: Future[List[Int]] = Future {
  makeSomeNumbers() //when this finishes,the Future is completed.
}

f onSuccess {
  case foo => println("I was completed when makeSomeNumbers finished")
}

而Promise可以产生可以手动完成的未来.

val p = Promise[String]()
val f = p.future

p success('hi') //when success is called,the Future is completed.

f onSuccess {
  case foo => println("I was completed because a Promise told me to do so")
}

传递给onSuccess的回调不会完成Future,它只会在Future完成并且执行某些操作时进行侦听.在Promises的情况下,您可以调用其成功方法来完成其关联的Future.

(编辑:李大同)

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

    推荐文章
      热点阅读