Properly handle execeptions thrown by Promises in the usePromise()
hook (#21408)
This commit is contained in:
parent
ee205c8fbc
commit
0e441b9fb8
1 changed files with 11 additions and 3 deletions
|
@ -52,15 +52,23 @@ export function usePromise<T>(
|
|||
const { signal } = controller;
|
||||
|
||||
async function handlePromise() {
|
||||
const value = await factory(signal);
|
||||
// Try to resolve the Promise, if it fails, check if it was aborted.
|
||||
try {
|
||||
callback(await factory(signal));
|
||||
} catch (error) {
|
||||
// Ignore errors caused by aborting the Promise.
|
||||
if (error instanceof Error && error.name === "AbortError") {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!signal.aborted) {
|
||||
callback(value);
|
||||
// Rethrow other errors.
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
handlePromise();
|
||||
|
||||
// Abort the Promise when the component unmounts, or the dependencies change.
|
||||
return () => controller.abort();
|
||||
}, deps);
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue