@@ -246,36 +246,32 @@ const useAsyncInternal = <R = UnknownResult, Args extends any[] = UnknownArgs>(
246
246
isMounted ( ) && CurrentPromise . is ( p ) ;
247
247
248
248
const executeAsyncOperation = ( ...args : Args ) : Promise < R > => {
249
- const promise : MaybePromise < R > = asyncFunction ( ...args ) ;
249
+ // async ensures errors thrown synchronously are caught (ie, bug when formatting api payloads)
250
+ // async ensures promise-like and synchronous functions are handled correctly too
251
+ // see https://github.com/slorber/react-async-hook/issues/24
252
+ const promise : Promise < R > = ( async ( ) => asyncFunction ( ...args ) ) ( ) ;
250
253
setCurrentParams ( args ) ;
251
- if ( promise instanceof Promise ) {
252
- CurrentPromise . set ( promise ) ;
253
- AsyncState . setLoading ( ) ;
254
- promise . then (
255
- result => {
256
- if ( shouldHandlePromise ( promise ) ) {
257
- AsyncState . setResult ( result ) ;
258
- }
259
- normalizedOptions . onSuccess ( result , {
260
- isCurrent : ( ) => CurrentPromise . is ( promise ) ,
261
- } ) ;
262
- } ,
263
- error => {
264
- if ( shouldHandlePromise ( promise ) ) {
265
- AsyncState . setError ( error ) ;
266
- }
267
- normalizedOptions . onError ( error , {
268
- isCurrent : ( ) => CurrentPromise . is ( promise ) ,
269
- } ) ;
254
+ CurrentPromise . set ( promise ) ;
255
+ AsyncState . setLoading ( ) ;
256
+ promise . then (
257
+ result => {
258
+ if ( shouldHandlePromise ( promise ) ) {
259
+ AsyncState . setResult ( result ) ;
270
260
}
271
- ) ;
272
- return promise ;
273
- } else {
274
- // We allow passing a non-async function (mostly for useAsyncCallback convenience)
275
- const syncResult : R = promise ;
276
- AsyncState . setResult ( syncResult ) ;
277
- return Promise . resolve < R > ( syncResult ) ;
278
- }
261
+ normalizedOptions . onSuccess ( result , {
262
+ isCurrent : ( ) => CurrentPromise . is ( promise ) ,
263
+ } ) ;
264
+ } ,
265
+ error => {
266
+ if ( shouldHandlePromise ( promise ) ) {
267
+ AsyncState . setError ( error ) ;
268
+ }
269
+ normalizedOptions . onError ( error , {
270
+ isCurrent : ( ) => CurrentPromise . is ( promise ) ,
271
+ } ) ;
272
+ }
273
+ ) ;
274
+ return promise ;
279
275
} ;
280
276
281
277
const getLatestExecuteAsyncOperation = useGetter ( executeAsyncOperation ) ;
0 commit comments