[英]What is the Python equivalent of a Promise in JavaScript?
我試圖了解什么是最好的代碼結構或設計模式,可以執行以下操作:
有一個名為get_data
的 function 將啟動一個套接字連接並開始等待返回一些數據的特定套接字事件。 一旦它得到數據,只有get_data
function 應該被返回。
所以在 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
將返回一個 object 您可以await
,就像async
function 調用一樣:
async def parse_data():
data = await get_data()
# process further
從 3.7 開始,Python 實際上有一個名為asyncio
的模塊,用於異步執行代碼,類似於 JavaScript 的 async/await 語法。
這是一個簡單的例子:
import asyncio
async def main():
print('Hello ...')
await asyncio.sleep(1)
print('... World!')
# Python 3.7+
asyncio.run(main())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.