惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

B
Blog RSS Feed
K
Kaspersky official blog
Forbes - Security
Forbes - Security
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
P
Proofpoint News Feed
G
GRAHAM CLULEY
V
Vulnerabilities – Threatpost
Security Latest
Security Latest
Scott Helme
Scott Helme
S
Securelist
美团技术团队
T
Threat Research - Cisco Blogs
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
S
SegmentFault 最新的问题
W
WeLiveSecurity
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Apple Machine Learning Research
Apple Machine Learning Research
The Cloudflare Blog
AI
AI
L
Lohrmann on Cybersecurity
S
Security Affairs
Cloudbric
Cloudbric
SecWiki News
SecWiki News
爱范儿
爱范儿
雷峰网
雷峰网
Engineering at Meta
Engineering at Meta
C
Cyber Attacks, Cyber Crime and Cyber Security
大猫的无限游戏
大猫的无限游戏
N
News and Events Feed by Topic
I
InfoQ
S
Secure Thoughts
AWS News Blog
AWS News Blog
A
About on SuperTechFans
Schneier on Security
Schneier on Security
酷 壳 – CoolShell
酷 壳 – CoolShell
The Last Watchdog
The Last Watchdog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
C
Check Point Blog
P
Palo Alto Networks Blog
博客园 - 【当耐特】
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Google DeepMind News
Google DeepMind News
Latest news
Latest news
I
Intezer
博客园_首页
C
CXSECURITY Database RSS Feed - CXSecurity.com
V
V2EX
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
L
LangChain Blog
D
Docker

博客园 - 悠哉大斌

AI Agent 安全沙箱技术对比:E2B、Cube Sandbox 与 Docker Sandboxes linux 升级 claude code的坑 debian(WSL) apt 代理配置 linux内核之Namespaces、Cgroups、Capabilities、Seccomp和Landlock 大语言模型推理中的隐藏瓶颈及其解决方法 Docker Sandboxes 技术是什么,和docker容器有什么区别 什么是 Docker Agent以及一个Docker Agent示例 windows wsl 安装 Temurin® JDK claude Code 和 codex 作为编程代理,前者使用typescript开发,后者使用rust,他们的决策依据是什么 Java 并发编程发展史与 java.util.concurrent 全景解析 LLM 真的改变了编码风格吗? 如果人工智能会犯错且不精确,为什么它正在改变世界? python闭包和function.__closure__特殊属性 python 的 dunder name和 sunder name 基于nodejs设计REST API的知名开源框架 windows上使用node-oracledb Thick 模式连接 Oracle 11g Claude Code CLI连接 DeepSeek V4模型后调用报400错误 python里对象(object)到底是什么 Python 泛型演变史 Python 类型别名的演变 Python 类型提示的演变史 PEP 593 新增的Annotated 类型 Alibaba AgentScope 和 microsoft agent framework 详细对比分析 spring AI Alibaba Agent Framework 和 agentscope有什么区别和联系 AI Agent协作模式以及主流开源框架对协作模式的支持 Tailscale 是如何接管 DNS 的? Agent = Model + Harness 使用rust编写typescript编译器的难点在什么地方,哪些数据结构是rust不擅长的? TypeScript/JavaScript 中的异步迭代语句 js中的生成器函数 Tailscale Serve and Funnel openclaw gateway的网络绑定模式 websocket协议和http协议有何依赖关系? MCP通信的双方是谁? claude code MCP 安装范围 如何在wsl2环境下给claude code cli 配置 playwright-mcp wsl的网络模式有哪几种,有哪些区别? AI Agent memory是什么? ai agent skills是什么? Go测试生态系统工具与最佳实践深度调研(聚焦认证授权系统) 线性代数中常见矩阵类型的概念关系思维导图 三种主流授权策略
Python 的协程模型和 JavaScript 的 async/await
悠哉大斌 · 2026-05-13 · via 博客园 - 悠哉大斌

Python 的协程模型和 JavaScript 的 async/await 非常像,因为:

Python 的 asyncio 在设计上大量借鉴了 JavaScript 的 Promise + Event Loop 模型。

尤其是:

JavaScript Python
async function async def
await await
Promise Future / Task
Event Loop Event Loop
单线程异步 IO 单线程异步 IO

所以如果你熟悉 JS,再学 Python 协程会轻松很多。


一、最直观对比

JavaScript

async function hello() {
    console.log("start");
    await fetch("/api");
    console.log("end");
}

Python

import asyncio

async def hello():
    print("start")
    await asyncio.sleep(1)
    print("end")

结构几乎一样。


二、两者核心思想完全一致

本质都是:

遇到 await
    ↓
暂停当前函数
    ↓
把控制权交回事件循环
    ↓
等待 IO 完成
    ↓
恢复执行

这就是:

协作式并发(cooperative concurrency)

三、对应关系

1. async function vs async def

JavaScript:

async function f() {}

Python:

async def f():
    pass

它们都:

  • 定义“异步函数”
  • 调用后不会立即执行完
  • 返回“可等待对象”

四、Promise vs Coroutine

这是两者一个重要区别。


JavaScript

async 函数返回:

Promise

例如:

async function f() {
    return 123;
}

console.log(f())

输出:

Promise { 123 }

Python

async def 返回:

coroutine object

例如:

async def f():
    return 123

print(f())

输出:

<coroutine object>

五、await 的意义相同

JS:

await fetch(...)

Python:

await session.get(...)

都表示:

“这里可能要等待,先切出去执行别的任务。”


六、事件循环也非常像


JavaScript Event Loop

浏览器 / Node.js:

call stack
task queue
microtask queue
event loop

Python asyncio Event Loop

ready queue
selector/epoll
callback queue
task scheduler

思想高度一致:

谁 IO 完成了
    ↓
恢复谁执行

七、Task 和 Promise 很像


JS

const p = fetch("/api");

p 是 Promise。


Python

task = asyncio.create_task(work())

task 是 Task。

都表示:

一个未来会完成的异步任务

八、并发执行方式也类似


JavaScript

await Promise.all([
    fetch("/a"),
    fetch("/b")
])

Python

await asyncio.gather(
    fetch_a(),
    fetch_b(),
)

几乎一模一样。


九、最大区别:Python 更底层

JS 的 async/await:

  • 主要围绕 Promise
  • 浏览器/Node 封装很多东西
  • 使用更“自动化”

Python:

  • coroutine
  • Future
  • Task
  • EventLoop

这些概念暴露更多。

所以 Python asyncio:

  • 更灵活
  • 也更复杂

十、Python 协程真正来源于生成器

这是和 JS 最大的历史区别。

JavaScript async:

Promise 驱动

而 Python 协程:

generator/yield 演化而来

所以 Python 有:

  • yield
  • yield from
  • send()
  • throw()
  • close()

这些底层机制。

JS 没这么复杂。


十一、Python 有“原生协程”和“生成器协程”历史包袱

早期 Python:

@asyncio.coroutine
def f():
    yield from ...

后来才有:

async def
await

所以 Python 协程体系有明显演化痕迹。

而 JS 基本一步到位:

callback
→ Promise
→ async/await

十二、Node.js 和 FastAPI 为什么都喜欢 async?

因为:

Web 服务本质是 IO 密集

大量时间在:

  • 等数据库
  • 等 HTTP
  • 等 Redis
  • 等磁盘

async 模型非常适合。

所以:

  • Node.js
  • FastAPI
  • aiohttp

都 heavily async。


十三、但 Python async 有一个重要限制

Python:

async != 多线程

它默认还是:

单线程事件循环

因此:

await cpu_heavy()

不会 magically 并行。

CPU 密集任务仍需要:

  • 多进程
  • 线程池
  • C扩展

这一点 JS 也类似。


十四、你如果有 JS 背景,会很快理解这些

你会发现:

JS 概念 Python 概念
Promise Future
Promise.all asyncio.gather
setTimeout asyncio.sleep
async function async def
await await
Event Loop Event Loop

真正需要重新适应的是:

Python coroutine object / Task / Future 的区别

这比 JS 更细。


十五、一个非常关键的区别

JS:

fetch("/api")

会立刻开始请求。


Python:

coro = fetch()

很多时候:

只是创建 coroutine object
并不会立刻执行

必须:

await coro

或者:

asyncio.create_task(coro)

才真正调度。

这是很多 JS 开发者刚转 Python 时最容易踩坑的地方。