@@ -352,26 +352,47 @@ export function runAsWorker<
352352 }
353353
354354 const { workerPort } = workerData as WorkerData
355- parentPort ! . on (
356- 'message' ,
357- ( { sharedBuffer, id, args } : MainToWorkerMessage < Parameters < T > > ) => {
358- // eslint-disable-next-line @typescript-eslint/no-floating-promises
359- ; ( async ( ) => {
360- const sharedBufferView = new Int32Array ( sharedBuffer )
361- let msg : WorkerToMainMessage < R >
362- try {
363- msg = { id, result : await fn ( ...args ) }
364- } catch ( error : unknown ) {
365- msg = {
366- id,
367- error,
368- properties : extractProperties ( error ) ,
355+
356+ try {
357+ parentPort ! . on (
358+ 'message' ,
359+ ( { sharedBuffer, id, args } : MainToWorkerMessage < Parameters < T > > ) => {
360+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
361+ ; ( async ( ) => {
362+ const sharedBufferView = new Int32Array ( sharedBuffer )
363+ let msg : WorkerToMainMessage < R >
364+ try {
365+ msg = { id, result : await fn ( ...args ) }
366+ } catch ( error : unknown ) {
367+ msg = { id, error, properties : extractProperties ( error ) }
369368 }
370- }
371- workerPort . postMessage ( msg )
369+ workerPort . postMessage ( msg )
370+ Atomics . add ( sharedBufferView , 0 , 1 )
371+ Atomics . notify ( sharedBufferView , 0 )
372+ } ) ( )
373+ } ,
374+ )
375+
376+ /**
377+ * @see https://github.com/un-ts/synckit/issues/94
378+ *
379+ * Starting the worker can fail, due to syntax error, for example. In that case
380+ * we just fail all incoming messages with whatever error message we got.
381+ * Otherwise incoming messages will hang forever waiting for a reply.
382+ */
383+ } catch ( error ) {
384+ parentPort ! . on (
385+ 'message' ,
386+ ( { sharedBuffer, id } : MainToWorkerMessage < Parameters < T > > ) => {
387+ const sharedBufferView = new Int32Array ( sharedBuffer )
388+ workerPort . postMessage ( {
389+ id,
390+ error,
391+ properties : extractProperties ( error ) ,
392+ } )
372393 Atomics . add ( sharedBufferView , 0 , 1 )
373394 Atomics . notify ( sharedBufferView , 0 )
374- } ) ( )
375- } ,
376- )
395+ } ,
396+ )
397+ }
377398}
0 commit comments