MCPcopy Index your code
hub / github.com/developit/greenlet / greenlet

Function greenlet

greenlet.js:5–67  ·  view source on GitHub ↗
(asyncFunction)

Source from the content-addressed store, hash-verified

3 * @public
4 */
5export default function greenlet(asyncFunction) {
6 // A simple counter is used to generate worker-global unique ID's for RPC:
7 let currentId = 0;
8
9 // Outward-facing promises store their "controllers" (`[request, reject]`) here:
10 const promises = {};
11
12 // Use a data URI for the worker's src. It inlines the target function and an RPC handler:
13 const script = '$$='+asyncFunction+';onmessage='+(e => {
14 /* global $$ */
15
16 // Invoking within then() captures exceptions in the supplied async function as rejections
17 Promise.resolve(e.data[1]).then(
18 v => $$.apply($$, v)
19 ).then(
20 // success handler - callback(id, SUCCESS(0), result)
21 // if `d` is transferable transfer zero-copy
22 d => {
23 postMessage([e.data[0], 0, d], [d].filter(x => (
24 (x instanceof ArrayBuffer) ||
25 (x instanceof MessagePort) ||
26 (self.ImageBitmap && x instanceof ImageBitmap)
27 )));
28 },
29 // error handler - callback(id, ERROR(1), error)
30 er => { postMessage([e.data[0], 1, '' + er]); }
31 );
32 });
33 const workerURL = URL.createObjectURL(new Blob([script]));
34 // Create an "inline" worker (1:1 at definition time)
35 const worker = new Worker(workerURL);
36
37 /** Handle RPC results/errors coming back out of the worker.
38 * Messages coming from the worker take the form `[id, status, result]`:
39 * id - counter-based unique ID for the RPC call
40 * status - 0 for success, 1 for failure
41 * result - the result or error, depending on `status`
42 */
43 worker.onmessage = e => {
44 // invoke the promise's resolve() or reject() depending on whether there was an error.
45 promises[e.data[0]][e.data[1]](e.data[2]);
46
47 // ... then delete the promise controller
48 promises[e.data[0]] = null;
49 };
50
51 // Return a proxy function that forwards calls to the worker & returns a promise for the result.
52 return function (args) {
53 args = [].slice.call(arguments);
54 return new Promise(function () {
55 // Add the promise controller to the registry
56 promises[++currentId] = arguments;
57
58 // Send an RPC call to the worker - call(id, params)
59 // The filter is to provide a list of transferables to send zero-copy
60 worker.postMessage([currentId, args], args.filter(x => (
61 (x instanceof ArrayBuffer) ||
62 (x instanceof MessagePort) ||

Callers 1

greenlet.test.jsFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…