### Install await-sync package Source: https://github.com/jimmywarting/await-sync/blob/main/README.md The command to install the await-sync library via npm. ```shell npm install await-sync ``` -------------------------------- ### Demonstrate ESM module sharing in worker threads Source: https://github.com/jimmywarting/await-sync/blob/main/README.md This example shows that multiple functions sharing the same ESM import will load it only once due to persistent worker threads. Subsequent calls to these functions are significantly faster as the module remains cached in the worker context. ```javascript const fn1 = toSync(async () => { globalThis.xyz ??= 0 console.log(globalThis.xyz++) const util = await import('./util.js') return new Uint8Array() }) const fn2 = toSync(async () => { globalThis.xyz ??= 0 console.log(globalThis.xyz++) const util = await import('./util.js') return new Uint8Array() }) fn1() // Warm up - 527ms (logs: 0) fn1() // instant - 24ms (logs: 1) fn2() // instant - 21ms (logs: 2) ``` -------------------------------- ### Use custom deserializers with await-sync Source: https://github.com/jimmywarting/await-sync/blob/main/README.md Shows how to implement custom deserialization logic to handle complex data types returned from the worker thread. This example uses a JSON-based deserializer to convert the Uint8Array response into a JavaScript object. ```javascript import { createWorker } from 'await-sync' const toSync = createWorker() function deserializer (uint8) { const text = new TextDecoder().decode(uint8) const json = JSON.parse(text) return json } const getJson = toSync( url => fetch(url).then(res => res.bytes()), deserializer ) const json = getJson('https://httpbin.org/get') ``` -------------------------------- ### Create Worker Instance and Wrap Async Functions (JavaScript) Source: https://context7.com/jimmywarting/await-sync/llms.txt Demonstrates how to create a worker instance using `createWorker` and wrap asynchronous functions for synchronous execution. It also shows how to use an `AbortSignal` to manage the worker's lifecycle. ```javascript import { createWorker } from 'await-sync' // Create a worker instance const toSync = createWorker() // Basic async-to-sync conversion function fetchData(url) { return fetch(url).then(res => res.bytes()) } const syncFetch = toSync(fetchData) const result = syncFetch('https://httpbin.org/get') // result is Uint8Array // With AbortController for cleanup const ctrl = new AbortController() const toSyncWithAbort = createWorker(ctrl.signal) const syncRequest = toSyncWithAbort(url => fetch(url).then(r => r.bytes())) const data = syncRequest('https://api.example.com/data') // Terminate worker when done ctrl.abort() ``` -------------------------------- ### Using Node.js v8 Serializer for Complex Data (JavaScript) Source: https://context7.com/jimmywarting/await-sync/llms.txt Demonstrates how to use Node.js's built-in `v8` serializer and deserializer with `await-sync` for efficient serialization of complex data structures like Maps, Sets, and typed arrays in a Node.js environment. ```javascript import { createWorker } from 'await-sync' import { deserialize } from 'node:v8' const toSync = createWorker() // Use v8 serializer for complex data structures const getComplexData = toSync(async url => { const { serialize } = await import('node:v8') const res = await fetch(url) const json = await res.json() return serialize(json) }, deserialize) const data = getComplexData('https://httpbin.org/get') // data is the parsed response with full type preservation ``` -------------------------------- ### Handle Empty Uint8Array Results with await-sync Source: https://context7.com/jimmywarting/await-sync/llms.txt Demonstrates how await-sync correctly handles functions returning empty Uint8Arrays, returning a zero-length array without errors. This ensures predictable behavior when dealing with functions that might produce no output. ```javascript import { createWorker } from 'await-sync' const toSync = createWorker() // Function that returns empty data const noOp = toSync(async () => { // Perform some side effect console.log('Worker executed') return new Uint8Array(0) }) const result = noOp() console.assert(result.byteLength === 0) // result is Uint8Array(0) ``` -------------------------------- ### Create synchronous functions from asynchronous code Source: https://github.com/jimmywarting/await-sync/blob/main/README.md Demonstrates how to use createWorker to transform an async function into a synchronous one. The worker function must return a Uint8Array to facilitate data transfer via Atomics. ```javascript import { createWorker } from 'await-sync' const toSync = createWorker() function workerCode (url) { return fetch(url).then(res => res.bytes()) } const syncAjax = toSync(workerCode) const uint8 = syncAjax('https://httpbin.org/get') const text = new TextDecoder().decode(uint8) const json = JSON.parse(text) ``` -------------------------------- ### Use NodeJS V8 serializer for data transfer Source: https://github.com/jimmywarting/await-sync/blob/main/README.md Demonstrates utilizing the built-in NodeJS v8 module for serializing and deserializing complex data structures when working within a Node environment. ```javascript import { deserialize } from 'node:v8' import { awaitSync } from 'await-sync' const getJson = awaitSync(async url => { const { serialize } = await import('node:v8') const res = await fetch(url) const json = await res.json() return serialize(json) }, deserialize) const json = getJson('https://httpbin.org/get') ``` -------------------------------- ### Synchronous Function Execution with Deserialization (JavaScript) Source: https://context7.com/jimmywarting/await-sync/llms.txt Illustrates using the `toSync` function to wrap an async function for synchronous execution and how to provide a custom `deserializer` to convert the `Uint8Array` output into a desired format, such as a JSON object. ```javascript import { createWorker } from 'await-sync' const toSync = createWorker() // Without deserializer - returns raw Uint8Array const syncAjax = toSync(url => fetch(url).then(res => res.bytes())) const uint8 = syncAjax('https://httpbin.org/get') // Convert Uint8Array to different types const text = new TextDecoder().decode(uint8) const json = JSON.parse(text) const blob = new Blob([uint8]) const arrayBuffer = uint8.buffer // With JSON deserializer function jsonDeserializer(uint8) { const text = new TextDecoder().decode(uint8) return JSON.parse(text) } const getJson = toSync( url => fetch(url).then(res => res.bytes()), jsonDeserializer ) const data = getJson('https://httpbin.org/get') // data is already parsed JSON object ``` -------------------------------- ### Importing ESM Modules in Worker Functions (JavaScript) Source: https://context7.com/jimmywarting/await-sync/llms.txt Explains how to dynamically import ES modules within worker functions using `await-sync`. Imports are cached across calls, improving performance for subsequent executions. ```javascript import { createWorker } from 'await-sync' const toSync = createWorker() // Import external modules inside the worker function const processWithLodash = toSync(async (data) => { const { default: _ } = await import('https://esm.sh/lodash') const result = _.groupBy(data, 'category') return new TextEncoder().encode(JSON.stringify(result)) }) // First call: ~500ms (cold start, imports lodash) const result1 = processWithLodash([ { name: 'apple', category: 'fruit' }, { name: 'carrot', category: 'vegetable' } ]) // Second call: ~20ms (worker warm, lodash cached) const result2 = processWithLodash([ { name: 'banana', category: 'fruit' } ]) ``` -------------------------------- ### Synchronously Reading Blob Contents (JavaScript) Source: https://context7.com/jimmywarting/await-sync/llms.txt Shows how to synchronously read the contents of a Blob by converting its data to a `Uint8Array` within the worker thread using `await-sync`. ```javascript import { createWorker } from 'await-sync' const toSync = createWorker() // Create a sync blob reader const readBlobSync = toSync(blob => blob.bytes()) // Read blob contents synchronously const blob = new Blob(['Hello, World!']) const bytes = readBlobSync(blob) // bytes is Uint8Array([72, 101, 108, 108, 111, ...]) const text = new TextDecoder().decode(bytes) // text is "Hello, World!" ``` -------------------------------- ### Terminate worker using AbortController Source: https://github.com/jimmywarting/await-sync/blob/main/README.md Demonstrates how to manually terminate a worker thread by passing an AbortSignal to the createWorker function and triggering the abort method on the controller. ```javascript const ctrl = new AbortController() createWorker(ctrl.signal) ctrl.abort() ``` -------------------------------- ### Error Handling in await-sync Workers Source: https://context7.com/jimmywarting/await-sync/llms.txt Illustrates how await-sync serializes and re-throws errors from worker functions in the main thread, preserving the original message and stack trace. This allows for robust error management in asynchronous operations executed synchronously. ```javascript import { createWorker } from 'await-sync' const toSync = createWorker() const riskyOperation = toSync(async (shouldFail) => { if (shouldFail) { throw new Error('Operation failed in worker') } return new TextEncoder().encode('success') }) // Error handling try { riskyOperation(true) } catch (error) { console.error(error.message) // "Operation failed in worker" console.error(error.stack) // Full stack trace from worker } // Successful execution const result = riskyOperation(false) const text = new TextDecoder().decode(result) // text is "success" ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.