


In Python, why does ws.send_text("1") have to wait for load_dataset("beans") to be executed before it is completed?
Analysis of the execution order of await keyword in Python asynchronous programming
This article discusses the execution order of await
keyword in Python asynchronous programming, especially the scenario of combining FastAPI and WebSocket. A common misconception is that the code after await
is executed immediately, and this is not always the case.
The following code example demonstrates this problem:
from fastapi import FastAPI, WebSocket from datasets import load_dataset app = FastAPI() @app.websocket("/") async def h(ws: WebSocket): await ws.accept() await ws.send_text("1") dataset = load_dataset("beans") # blocking operation await ws.send_text("2")
Intuitively, we expect "1" to be sent first, then load the dataset, and finally "2". But in reality, the sending of "1" will block until load_dataset("beans")
completes. This is because load_dataset("beans")
is a synchronous (blocking) function that prevents subsequent execution of the asynchronous function.
In order to observe the execution order more clearly, we modify the code and add the timestamp:
from datetime import datetime from datasets import load_dataset from fastapi import FastAPI, WebSocket from fastapi.responses import HTMLResponse app = FastAPI() # ... (HTML code remains the same) ... @app.websocket("/ws") async def h(ws: WebSocket): await ws.accept() await ws.send_text(f"1: {datetime.now()}") dataset = load_dataset("beans") print(f"time: {datetime.now()} => dataset: {dataset}") await ws.send_text(f"2: {datetime.now()}") While True: data = await ws.receive_text() await ws.send_text(f"Message text was: {data}, datetime: {datetime.now()}")
Run the modified code and you will find that "1" is indeed sent to the client first, and the browser receives the websocket information. This proves that ws.send_text("1")
is executed first. However, the blocking feature of load_dataset("beans")
results in a sending delay of "2".
in conclusion
await
keyword only waits for the asynchronous operation to complete. If await
is followed by a synchronous function, the execution of this synchronous function will block the entire asynchronous function until the synchronous function is executed. Therefore, in asynchronous functions, blocking operations should be avoided as much as possible, or asynchronous alternatives should be used to improve efficiency and response speed. In the above example, if load_dataset
has an asynchronous version, it should be used first.
The above is the detailed content of In Python, why does ws.send_text("1") have to wait for load_dataset("beans") to be executed before it is completed?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Binance Square is a social media platform provided by Binance Exchange, aiming to provide users with a space to communicate and share information related to cryptocurrencies. This article will explore the functions, reliability and user experience of Binance Plaza in detail to help you better understand this platform.

The latest download tutorial for Ouyi OKX6.118.0 version: 1. Click on the quick link in the article; 2. Click on the download (if you are a web user, please register the information first). The latest Android version v6.118.0 optimizes some functions and experiences to make trading easier. Update the app now to experience a more extreme trading experience.

As the world's leading cryptocurrency exchange, Binance is always committed to providing users with a safe and convenient trading experience. Over time, Binance has continuously optimized its platform features and user interface to meet the changing needs of users. In 2025, Binance launched a new login portal aimed at further improving the user experience.

As the world's leading cryptocurrency exchange, Binance is always committed to providing users with a safe and convenient trading experience. Over time, Binance has continuously optimized its platform features and user interface to meet the changing needs of users. In 2025, Binance launched a new login portal aimed at further improving the user experience.

Eagle is a powerful image database software with built-in crawler function that can batch capture pictures on Huabaiwang to meet your needs for image management. Eagle not only automatically recognizes the tone of the picture, but also supports finding the picture through color. In addition, it also provides various functions such as shape search, source search and size search to help you easily manage and find pictures. Whether you are using Windows, Mac or ChromeOS, Eagle can run smoothly in various environments to meet your multi-platform needs. Eagle also provides convenient browser plug-ins that support batch saving of pictures on the current web page. You can quickly save screenshots, original web page images or local files, and use simple drag and drop operations to transfer your favorite pictures

Python can run on a variety of platforms, including our common ones: Windows, Unix, Linux, and Macintosh. This article will introduce in detail the process of installing Python in Windows operating system. My operating system is Windows 7, 32-bit version. When installing Python, we can choose to install it from the source code or select the already compiled binary version for installation. I chose the latter here. Step 1 Download the installation package. We download the installation package of Python from the official Python website: http://www.python.org. The version I selected is: python-3.3.2.msi click to download, I

1. The Origin of .NETCore When talking about .NETCore, we must not mention its predecessor .NET. Java was in the limelight at that time, and Microsoft also favored Java. The Java virtual machine on the Windows platform was developed by Microsoft based on JVM standards. It is said to be the best performance Java virtual machine at that time. However, Microsoft has its own little abacus, trying to bundle Java with the Windows platform and add some Windows-specific features. Sun's dissatisfaction with this led to a breakdown of the relationship between the two parties, and Microsoft then launched .NET. .NET has borrowed many features of Java since its inception and gradually surpassed Java in language features and form development. Java in version 1.6

The USDT TRC20 transfer fee is affected by network congestion, transaction size and user-selected rates. Optimization fees can be achieved by selecting transaction time, adjusting rates and using batch transactions.
