Created
July 25, 2022 12:16
-
-
Save spencerfeng/77dc4e6f4df46fb7d664c636bc21c885 to your computer and use it in GitHub Desktop.
For tutorial: Create an abortable API using AbortController and AbortSignal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const abortableSearchItems = ( | |
searchString: string, | |
signal: AbortSignal | |
): Promise<Item[]> => { | |
if (signal.aborted) { | |
return Promise.reject(new Error("searchAborted")); | |
} | |
return new Promise((resolve, reject) => { | |
const abortSearchHandler = () => { | |
reject(new Error("searchAborted")); | |
}; | |
searchItemsAPI(searchString) | |
.then((results) => resolve(results)) | |
.catch((error) => reject(error)) | |
.finally(() => { | |
signal.removeEventListener("abort", abortSearchHandler); | |
}); | |
signal.addEventListener("abort", abortSearchHandler); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment