How can I create a cancellable async function in javascript
- User
How can I create a cancellable async function in javascript
Assistant
Here's how to create a cancellable async function using AbortController:
function cancellableAsyncOperation(signal) { return new Promise((resolve, reject) => { // Check if already aborted if (signal.aborted) { return reject(new Error('Operation was cancelled')); } // Setup abort listener const abortListener = () => { clearTimeout(timeoutId); reject(new Error('Operation was cancelled')); }; signal.addEventListener('abort', abortListener); // Your async operation (using setTimeout as example) const timeoutId = setTimeout(() => { signal.removeEventListener('abort', abortListener); resolve('Operation completed successfully'); }, 5000); }); } // Usage: async function example() { const controller = new AbortController(); const signal = controller.signal; try { // Cancel after 2 seconds (before the operation completes) setTimeout(() => controller.abort(), 2000); const result = await cancellableAsyncOperation(signal); console.log(result); } catch (error) { console.log(error.message); } } example();
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.