javascript - JavaScript 中 Promise 的 Python 等价物是什么?

标签 javascript python promise

我试图了解什么是最好的代码结构或设计模式,可以执行以下操作:
有一个名为 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/

相关文章:

python - 选择什么 HTML 解析器以及为什么 BeautifulSoup 不起作用?

javascript - go 函数内的await js 异步函数(promise)

javascript - 为什么这个node-mysql插入会产生一个数组?

javascript - 使用 Protractor 使用部分文本来控制重定向

传递路径时发生 Javascript ReferenceError

Python如何在其中也包含字符串的列表中获取数字总和

Python 继承 : Is it necessary to explicitly call the parents constructor and destructor?

javascript - 无法从 Node 模块中的异步 waterfall 获取返回值

javascript - jQuery - 使用嵌套 setTimeout 暂停 for 循环

javascript - 当到达视口(viewport)点时,然后转动我的侧边栏