如何将回调转换为Promise

编程入门 行业动态 更新时间:2024-10-18 08:28:07
本文介绍了如何将回调转换为Promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用play框架和Apache Kafka。

I am using play framework and Apache Kafka.

我有一个POST方法向Kafka发送消息。 Kafka有一个API方法

I have a POST method which sends a message to Kafka. Kafka has an API method

public java.util.concurrent.Future send(ProducerRecord record ,回调回调)

其中Javadoc表示

of which the Javadoc says

在确认发送后,异步向主题发送记录并调用提供的回调。

Asynchronously send a record to a topic and invoke the provided callback when the send has been acknowledged.

我使用play框架公开此功能。我想从Controller方法返回一个 Promise< Result> ,但无法弄清楚如何以非阻塞的方式实现。有人可以帮我解决这个问题吗?

I am exposing this functionality using the play framework. I want to return a Promise<Result> from the Controller method but can't figure out how to implement this in a non-blocking way. Can someone help me with this?

推荐答案

/stackoverflow/questions/30956704/java-scala-future-driven-by-a-callback>这是一个。

After some searching found the answer with some help from this one.

以下是代码

RedeemablePromise<Result> promise = RedeemablePromise.empty(); kafkaProducer.send(record, (metadata, ex) -> { if (ex != null) { promise.failure(ex); } else { promise.success(created(Json.toJson(new ProduceResult()))); } });

更多推荐

如何将回调转换为Promise

本文发布于:2023-11-25 15:20:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630275.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   回调   如何将   Promise

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!