我试图了解什么是最好的代码结构或设计模式,可以执行以下操作:
有一个名为 get_data
的函数这将启动一个套接字连接,并将开始等待一个特定的套接字事件,该事件将返回一些数据。一旦它得到数据,只有 get_data
应该返回函数。
所以在 JS 中它会非常简单,如下所示:
(请记住,此代码片段是一个示例,它并不意味着是一个工作代码)
const getData = async ()=>{
return new Promise((resolve, reject)=>{
const socket = socket()
socket.on("message", (data)=>{
resolve(data)
})
socket.connect("localhost")
});
}
const parseData = async () => {
const data = await getData()
// do something with the data
}
但是,使用 python,我完全不知道如何达到相同的结果。我如何将它翻译成python?这里将使用什么策略?
我现在能想到的唯一方法是这样的:
def get_data():
socket = socket()
my_data = None
@socket.event
def message(data):
nonlocal my_data
my_data = data
socket.connect("localhost")
while not my_data
time.sleep(0.3)
socket.disconnect()
return my_data
def parse_data():
data = get_data()
# do something with the data
最佳答案
如果您想将基于回调的 API 转换为 async
API,您可能正在寻找 asyncio.Future
.
稍微修改一下你的稻草人代码:
import asyncio
def get_data():
# create a future
future = asyncio.Future()
# create a socket
socket = socket()
# connect callbacks
@socket.on("message")
def on_message(data):
future.set_result(data)
@socket.on("error")
def on_error(error):
future.set_exception(error)
# create a background task that will communicate with the socket
# and invoke the callbacks
@asyncio.create_task
async def communicate():
socket.connect('localhost')
socket.communicate()
# return the future
return future
调用get_data
将返回一个您可以 await
的对象就像 async
函数调用:async def parse_data():
data = await get_data()
# process further
关于javascript - JavaScript 中 Promise 的 Python 等价物是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66940979/