You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyScript中asyncio事件顺序不符,如何等待getWords执行完成?

问题解决:让程序等待异步函数执行完成后再输出

问题原因

你当前的代码用asyncio.ensure_future(getWords())只是把异步协程提交到事件循环,但不会等待它执行完毕,所以后续的print("4. ...")会直接运行;同时getWords内部的my_Words是局部变量,外部无法获取到异步请求的结果。

修改方案

  1. 让getWords函数返回异步请求得到的结果
  2. 使用await关键字等待getWords执行完成,确保顺序执行并接收返回值

修改后的完整代码

from request import request
import asyncio
import json

async def getWords():
    print("2. INSIDE GETWORDS:")
    baseurl = "http://localhost:4000/wordscape"

    body = json.dumps({"sqlline": sqlline})
    headers = {"Content-type": "application/json"}
    response = await request(f"{baseurl}/read", body=body, method="POST", headers=headers)

    my_Words = await response.string()
    print("3. MYWORDS inside getWords:", my_Words)
    return my_Words  # 返回异步请求结果

sqlline = "select upper(word) as word from dictionary.dictionary_words_20230103 where word = 'help'\n"
print("1. BUILD SQL:", sqlline)
my_Words = await getWords()  # 等待协程执行完成并获取结果
print("4. ####WORDS RETURNED FROM getWords:", my_Words)

替代方案(若顶层await不兼容)

如果你的环境不支持顶层await,可以把逻辑封装到主协程中,用asyncio.run触发执行:

from request import request
import asyncio
import json

async def getWords():
    print("2. INSIDE GETWORDS:")
    baseurl = "http://localhost:4000/wordscape"

    body = json.dumps({"sqlline": sqlline})
    headers = {"Content-type": "application/json"}
    response = await request(f"{baseurl}/read", body=body, method="POST", headers=headers)

    my_Words = await response.string()
    print("3. MYWORDS inside getWords:", my_Words)
    return my_Words

async def main():
    sqlline = "select upper(word) as word from dictionary.dictionary_words_20230103 where word = 'help'\n"
    print("1. BUILD SQL:", sqlline)
    my_Words = await getWords()
    print("4. ####WORDS RETURNED FROM getWords:", my_Words)

asyncio.run(main())

修改后输出顺序

1. BUILD SQL: select upper(word) as word from dictionary.dictionary_words_20230103 where word = 'help'

2. INSIDE GETWORDS:
3. MYWORDS inside getWords: [
  {
    "word": "HELP"
  }
]
4. ####WORDS RETURNED FROM getWords: [
  {
    "word": "HELP"
  }
]

内容的提问来源于stack exchange,提问作者99Valk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 04:21:50