1- /**
2- * Checks whether an object implements a Transferable interface
3- * @param {* } obj
4- * obj to check for Transferable interface
5- */
6- function isTransferable ( obj ) {
7- // https://developer.mozilla.org/en-US/docs/Web/API/Transferable
8- return (
9- obj instanceof ArrayBuffer ||
10- obj instanceof MessagePort ||
11- obj instanceof ImageBitmap
12- ) ;
13- }
14-
151/** Move an async function into its own thread.
162 * @param {Function } asyncFunction An (async) function to run in a Worker.
173 * @public
@@ -26,27 +12,17 @@ export default function greenlet(asyncFunction) {
2612 'onmessage=(' + (
2713 // userFunc() is the user-supplied async function
2814 userFunc => e => {
29- // To check whether an obj is transferable
30- function isTransferable ( obj ) {
31- // https://developer.mozilla.org/en-US/docs/Web/API/Transferable
32- return (
33- obj instanceof ArrayBuffer ||
34- obj instanceof MessagePort ||
35- obj instanceof ImageBitmap
36- ) ;
37- }
3815 // Invoking within then() captures exceptions in userFunc() as rejections
3916 Promise . resolve ( e . data [ 1 ] ) . then (
4017 userFunc . apply . bind ( userFunc , userFunc )
4118 ) . then (
4219 // success handler - callback(id, SUCCESS(0), result)
20+ // if `d` is transferrable transfer zero-copy
4321 d => {
44- if ( isTransferable ( d ) ) {
45- postMessage ( [ e . data [ 0 ] , 0 , d ] , [ d ] ) ;
46- }
47- else {
48- postMessage ( [ e . data [ 0 ] , 0 , d ] ) ;
49- }
22+ postMessage ( [ e . data [ 0 ] , 0 , d ] , (
23+ d instanceof ArrayBuffer ||
24+ d instanceof MessagePort ||
25+ d instanceof ImageBitmap ) ? [ d ] : [ ] ) ;
5026 } ,
5127 // error handler - callback(id, ERROR(1), error)
5228 er => { postMessage ( [ e . data [ 0 ] , 1 , '' + er ] ) ; }
@@ -85,7 +61,12 @@ export default function greenlet(asyncFunction) {
8561 promises [ ++ currentId ] = arguments ;
8662
8763 // Send an RPC call to the worker - call(id, params)
88- worker . postMessage ( [ currentId , args ] , args . filter ( x => isTransferable ( x ) ) ) ;
64+ // The filter is to provide a list of transferrables to send zero-copy
65+ worker . postMessage ( [ currentId , args ] , args . filter ( x => (
66+ x instanceof ArrayBuffer ||
67+ x instanceof MessagePort ||
68+ x instanceof ImageBitmap
69+ ) ) ) ;
8970 } ) ;
9071 } ;
9172}
0 commit comments