Coding
AI Prompt for Async Functions
Write robust async functions with this AI prompt: timeouts, retries with backoff, parallel calls, cancellation, and graceful error handling built in.
The prompt
Role: You are a [LANGUAGE] expert in asynchronous programming who writes async code that never hangs and always handles failure. Context: Language: [LANGUAGE] ([ASYNC_MODEL: async/await / promises / callbacks / etc.]). Task: [TASK_DESCRIPTION]. Requirements: timeout [TIMEOUT], retries [RETRY_POLICY], on failure: [FAILURE_MODE: throw / return partial data / fallback value]. Task: 1) Write the async function using idiomatic [ASYNC_MODEL]. 2) Implement the timeout so a hung operation cannot block forever. 3) Implement retries with exponential backoff where [RETRY_POLICY] requires it. 4) Handle errors per [FAILURE_MODE] — collect partial results with warnings if that is the mode. 5) Show a usage example with proper error handling by the caller. Format: Main function in a code block, then helper functions (retry, timeout) if needed, then the usage example. Constraints: No unhandled promise rejections or swallowed errors. Every async operation must have a timeout or cancellation path. Use the language's standard primitives, not hand-rolled event loops.
Variables to fill in
Replace each [variable] in the prompt with your own details:
[LANGUAGE] [ASYNC_MODEL] [TASK_DESCRIPTION] [TIMEOUT] [RETRY_POLICY] [FAILURE_MODE]
Example input
LANGUAGE=JavaScript, TASK=fetch user profile and their recent orders from two endpoints, TIMEOUT=5s, RETRIES=3 with backoff, FAIL_MODE=return partial data with warnings
How to use this prompt
Specify timeouts and retry policy upfront — async code without them is a production incident waiting to happen. Define the failure mode: throw, return partial, or fallback.
Tips for the best results
- Ask for a cancellation/abort version too if your UI needs to cancel in-flight requests.
- Have it list every failure mode of the external call and how each is handled.
- Test the timeout path deliberately — it is the path most developers never test.
Frequently asked questions
What if one call can fail but others should continue?
Say so in the TASK — the prompt supports graceful degradation, and the result includes partial output plus collected errors.
What is the biggest mistake in hand-written async code?
Missing timeouts and swallowed errors. This prompt forces both: every async operation gets a timeout path and every failure mode is handled explicitly.