Your port’s board now gives up on Hollins Green after half a second, and it marks Quarry Hill as having no answer. That second mark is a little unfair. Quarry Hill’s new kiosk fails only its first request of the morning, so asking it again a moment later would get its holds onto the board.
Owen’s Python script already does this, with a try and except around the await. In this lesson, you’ll port that retry and see that error handling in async JavaScript works the way it does in Python.
Catch the Failure Where You Await It
Owen’s script keeps the retry in a small async function, check_with_retry(). It asks the kiosk once, and if that raises ConnectionError, it prints the error, pauses for RETRY_PAUSE, and asks once more. The script below checks Quarry Hill alone and times the run. Its KIOSKS table and check_kiosk() stand-in are the same as in the earlier lessons, so the new part is check_with_retry() in the middle:
import asyncio
import time
KIOSKS = {
"Northgate": {"delay": 0.12, "holds": 14},
"Eastfield": {"delay": 0.25, "holds": 9},
"Hollins Green": {"delay": 0.9, "holds": 6},
"Quarry Hill": {"delay": 0.08, "holds": 3, "fails_first": True},
}
RETRY_PAUSE = 0.2
async def check_kiosk(branch):
kiosk = KIOSKS[branch]
await asyncio.sleep(kiosk["delay"])
if kiosk.get("fails_first"):
kiosk["fails_first"] = False
raise ConnectionError(f"{branch} kiosk is not answering")
return {"branch": branch, "holds": kiosk["holds"]}
async def check_with_retry(branch):
try:
return await check_kiosk(branch)
except ConnectionError as err:
print(f"{err}, asking again")
await asyncio.sleep(RETRY_PAUSE)
return await check_kiosk(branch)
async def main():
start = time.perf_counter()
kiosk = await check_with_retry("Quarry Hill")
print(f"{kiosk['branch']}: {kiosk['holds']} holds waiting")
elapsed = time.perf_counter() - start
print(f"Checked in {elapsed:.1f} s")
if __name__ == "__main__":
asyncio.run(main())