Handling a Promise You Await Later
Owen’s board also shows yesterday’s total, from a small history file the script writes each
morning. His Python script starts reading it before asking the kiosks, with
asyncio.create_task(), so the file loads while the kiosks answer. The read itself runs in
asyncio.to_thread(), because reading a file would block. After the board, the script awaits the
task inside try, and a missing file means there’s no history yet:
HISTORY = Path("history.json")
async def load_history():
text = await asyncio.to_thread(
HISTORY.read_text, encoding="utf-8"
)
return json.loads(text)["total"]
async def main():
history = asyncio.create_task(load_history())
# ... await gather() on the kiosks, then print the board's four lines
try:
yesterday = await history
except FileNotFoundError:
yesterday = "no history yet"
print(f"Total: {total} holds waiting (yesterday: {yesterday})")
On the first morning there’s no history.json yet. The read fails, the except clause catches
the error at the await, and the board ends with yesterday’s part reading “no history yet”:
Northgate: 14 holds waiting
Eastfield: 9 holds waiting
Hollins Green: 6 holds waiting
Quarry Hill: no answer (Quarry Hill kiosk is not answering)
Total: 29 holds waiting (yesterday: no history yet)