├── .editorconfig ├── .gitattributes ├── .github └── workflows │ └── main.yml ├── .gitignore ├── .npmrc ├── index.d.ts ├── index.js ├── index.test-d.ts ├── license ├── package.json ├── readme.md └── test.js /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = tab 5 | end_of_line = lf 6 | charset = utf-8 7 | trim_trailing_whitespace = true 8 | insert_final_newline = true 9 | 10 | [*.yml] 11 | indent_style = space 12 | indent_size = 2 13 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto eol=lf 2 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | - push 4 | - pull_request 5 | jobs: 6 | test: 7 | name: Node.js ${{ matrix.node-version }} 8 | runs-on: ubuntu-latest 9 | strategy: 10 | fail-fast: false 11 | matrix: 12 | node-version: 13 | - 20 14 | - 18 15 | steps: 16 | - uses: actions/checkout@v4 17 | - uses: actions/setup-node@v4 18 | with: 19 | node-version: ${{ matrix.node-version }} 20 | - run: npm install 21 | - run: npm test 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | yarn.lock 3 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | package-lock=false 2 | -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | import {type Asyncify, type SetReturnType} from 'type-fest'; 2 | 3 | type AnyFunction = (...arguments_: any) => unknown; 4 | 5 | type MakeAsynchronous = T & { 6 | /** 7 | The function returned by `makeAsynchronous` and `makeAsynchronousIterable` has an additional method which allows an [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) to be provided. 8 | 9 | @example 10 | ``` 11 | import makeAsynchronous from 'make-asynchronous'; 12 | 13 | const fn = makeAsynchronous(number => { 14 | return performExpensiveOperation(number); 15 | }); 16 | 17 | const controller = new AbortController(); 18 | const timeoutId = setTimeout(() => { 19 | controller.abort(); 20 | }, 1000); // 1 second timeout 21 | 22 | const result = await fn.withSignal(controller.signal)(2); 23 | clearTimeout(timeoutId); 24 | 25 | console.log(result); 26 | //=> 345342 27 | ``` 28 | */ 29 | withSignal(signal: AbortSignal): T; 30 | }; 31 | 32 | /** 33 | Make a synchronous function asynchronous by running it in a worker. 34 | 35 | Returns a wrapped version of the given function which executes asynchronously in a background thread (meaning it will not block the main thread). 36 | 37 | The given function is serialized, so you cannot use any variables or imports from outside the function scope. You can instead pass in arguments to the function. 38 | 39 | @example 40 | ``` 41 | import makeAsynchronous from 'make-asynchronous'; 42 | 43 | const fn = makeAsynchronous(number => { 44 | return performExpensiveOperation(number); 45 | }); 46 | 47 | console.log(await fn(2)); 48 | //=> 345342 49 | ``` 50 | */ 51 | export default function makeAsynchronous(function_: T): MakeAsynchronous>; 52 | 53 | type IterableFunctionValue = T extends ((...arguments_: any) => AsyncIterable | Iterable) ? Value : unknown; 54 | 55 | /** 56 | Make the iterable returned by a function asynchronous by running it in a worker. 57 | 58 | Returns a wrapped version of the given function which executes asynchronously in a background thread (meaning it will not block the main thread). 59 | 60 | The given function is serialized, so you cannot use any variables or imports from outside the function scope. You can instead pass in arguments to the function. 61 | 62 | @example 63 | ``` 64 | import {makeAsynchronousIterable} from 'make-asynchronous'; 65 | 66 | const fn = makeAsynchronousIterable(function * (number) { 67 | yield * performExpensiveOperation(number); 68 | }); 69 | 70 | for await (const number of fn(2)) { 71 | console.log(number); 72 | } 73 | ``` 74 | */ 75 | export function makeAsynchronousIterable AsyncIterable | Iterable>(function_: T): MakeAsynchronous>>>; 76 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | import Worker from 'web-worker'; 2 | import {pEvent} from 'p-event'; 3 | 4 | const isNode = Boolean(globalThis.process?.versions?.node); 5 | 6 | const makeBlob = content => new globalThis.Blob([content], {type: 'text/javascript'}); 7 | 8 | // TODO: Remove this when https://github.com/developit/web-worker/issues/30 is fixed. 9 | const makeDataUrl = content => { 10 | const data = globalThis.Buffer.from(content).toString('base64'); 11 | return `data:text/javascript;base64,${data}`; 12 | }; 13 | 14 | function createWorker(content) { 15 | let url; 16 | let worker; 17 | 18 | const cleanup = () => { 19 | if (url) { 20 | URL.revokeObjectURL(url); 21 | } 22 | 23 | worker?.terminate(); 24 | }; 25 | 26 | if (isNode) { 27 | worker = new Worker(makeDataUrl(content), {type: 'module'}); 28 | } else { 29 | url = URL.createObjectURL(makeBlob(content)); 30 | worker = new Worker(url, {type: 'module'}); 31 | } 32 | 33 | return { 34 | worker, 35 | cleanup, 36 | }; 37 | } 38 | 39 | const makeContent = function_ => 40 | ` 41 | globalThis.onmessage = async ({data: arguments_}) => { 42 | try { 43 | const output = await (${function_.toString()})(...arguments_); 44 | globalThis.postMessage({output}); 45 | } catch (error) { 46 | globalThis.postMessage({error}); 47 | } 48 | }; 49 | `; 50 | 51 | export default function makeAsynchronous(function_) { 52 | const content = makeContent(function_); 53 | const setup = () => createWorker(content); 54 | 55 | async function run({worker, arguments_}) { 56 | const promise = pEvent(worker, 'message', { 57 | rejectionEvents: ['error', 'messageerror'], 58 | }); 59 | 60 | worker.postMessage(arguments_); 61 | 62 | const {data: {output, error}} = await promise; 63 | 64 | if (error) { 65 | throw error; 66 | } 67 | 68 | return output; 69 | } 70 | 71 | const fn = async (...arguments_) => { 72 | const {worker, cleanup} = setup(); 73 | 74 | try { 75 | return await run({arguments_, worker}); 76 | } finally { 77 | cleanup(); 78 | } 79 | }; 80 | 81 | fn.withSignal = signal => async (...arguments_) => { 82 | signal.throwIfAborted(); 83 | 84 | const {worker, cleanup} = setup(); 85 | 86 | const abortPromise = pEvent(signal, [], { 87 | rejectionEvents: ['abort'], 88 | }); 89 | 90 | try { 91 | return await Promise.race([ 92 | run({arguments_, worker}), 93 | abortPromise, 94 | ]); 95 | } catch (error) { 96 | signal.throwIfAborted(); 97 | throw error; 98 | } finally { 99 | abortPromise.cancel(); 100 | cleanup(); 101 | } 102 | }; 103 | 104 | return fn; 105 | } 106 | 107 | const makeIterableContent = function_ => 108 | ` 109 | const nothing = Symbol('nothing'); 110 | let iterator = nothing; 111 | 112 | globalThis.onmessage = async ({data: arguments_}) => { 113 | try { 114 | if (iterator === nothing) { 115 | iterator = await (${function_.toString()})(...arguments_); 116 | } 117 | 118 | const output = await iterator.next(); 119 | globalThis.postMessage({output}); 120 | } catch (error) { 121 | globalThis.postMessage({error}); 122 | } 123 | }; 124 | `; 125 | 126 | export function makeAsynchronousIterable(function_) { 127 | const content = makeIterableContent(function_); 128 | const setup = () => createWorker(content); 129 | 130 | const fn = (...arguments_) => ({ 131 | async * [Symbol.asyncIterator]() { 132 | const {worker, cleanup} = setup(); 133 | 134 | try { 135 | let isFirstMessage = true; 136 | 137 | while (true) { 138 | const promise = pEvent(worker, 'message', { 139 | rejectionEvents: ['error', 'messageerror'], 140 | }); 141 | 142 | worker.postMessage(isFirstMessage ? arguments_ : undefined); 143 | isFirstMessage = false; 144 | 145 | const {data: {output, error}} = await promise; // eslint-disable-line no-await-in-loop 146 | 147 | if (error) { 148 | throw error; 149 | } 150 | 151 | const {value, done} = output; 152 | 153 | if (done) { 154 | break; 155 | } 156 | 157 | yield value; 158 | } 159 | } finally { 160 | cleanup(); 161 | } 162 | }, 163 | }); 164 | 165 | fn.withSignal = signal => (...arguments_) => ({ 166 | async * [Symbol.asyncIterator]() { 167 | signal.throwIfAborted(); 168 | 169 | const {worker, cleanup} = setup(); 170 | 171 | const abortPromise = pEvent(signal, [], { 172 | rejectionEvents: ['abort'], 173 | }); 174 | 175 | try { 176 | let isFirstMessage = true; 177 | 178 | while (true) { 179 | const promise = Promise.race([ 180 | pEvent(worker, 'message', { 181 | rejectionEvents: ['error', 'messageerror'], 182 | }), 183 | abortPromise, 184 | ]); 185 | 186 | worker.postMessage(isFirstMessage ? arguments_ : undefined); 187 | isFirstMessage = false; 188 | 189 | const {data: {output, error}} = await promise; // eslint-disable-line no-await-in-loop 190 | 191 | if (error) { 192 | throw error; 193 | } 194 | 195 | const {value, done} = output; 196 | 197 | if (done) { 198 | break; 199 | } 200 | 201 | yield value; 202 | } 203 | } catch (error) { 204 | signal.throwIfAborted(); 205 | throw error; 206 | } finally { 207 | abortPromise.cancel(); 208 | cleanup(); 209 | } 210 | }, 211 | }); 212 | 213 | return fn; 214 | } 215 | -------------------------------------------------------------------------------- /index.test-d.ts: -------------------------------------------------------------------------------- 1 | import {expectType} from 'tsd'; 2 | import makeAsynchronous, {makeAsynchronousIterable} from './index.js'; 3 | 4 | const {signal} = new AbortController(); 5 | 6 | const fn = makeAsynchronous((number: number) => number * 2); // eslint-disable-line @typescript-eslint/no-unsafe-assignment 7 | 8 | expectType>(fn(2)); 9 | expectType>(fn.withSignal(signal)(2)); 10 | 11 | const fn2 = makeAsynchronousIterable(function * () { // eslint-disable-line @typescript-eslint/no-unsafe-assignment 12 | for (let number = 1; ; number++) { 13 | yield number; 14 | } 15 | }); 16 | 17 | expectType>(fn2()); 18 | expectType>(fn2.withSignal(signal)()); 19 | -------------------------------------------------------------------------------- /license: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Sindre Sorhus (https://sindresorhus.com) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "make-asynchronous", 3 | "version": "1.0.1", 4 | "description": "Make a synchronous function asynchronous by running it in a worker", 5 | "license": "MIT", 6 | "repository": "sindresorhus/make-asynchronous", 7 | "funding": "https://github.com/sponsors/sindresorhus", 8 | "author": { 9 | "name": "Sindre Sorhus", 10 | "email": "sindresorhus@gmail.com", 11 | "url": "https://sindresorhus.com" 12 | }, 13 | "type": "module", 14 | "exports": { 15 | "types": "./index.d.ts", 16 | "default": "./index.js" 17 | }, 18 | "sideEffects": false, 19 | "engines": { 20 | "node": ">=18" 21 | }, 22 | "scripts": { 23 | "test": "xo && ava && tsd" 24 | }, 25 | "files": [ 26 | "index.js", 27 | "index.d.ts" 28 | ], 29 | "keywords": [ 30 | "function", 31 | "asynchronous", 32 | "async", 33 | "thread", 34 | "dispatch", 35 | "synchronous", 36 | "sync", 37 | "web", 38 | "worker", 39 | "thread", 40 | "cpu", 41 | "expensive", 42 | "pool" 43 | ], 44 | "dependencies": { 45 | "p-event": "^6.0.0", 46 | "type-fest": "^4.6.0", 47 | "web-worker": "1.2.0" 48 | }, 49 | "devDependencies": { 50 | "ava": "^5.3.1", 51 | "delay": "^6.0.0", 52 | "in-range": "^3.0.0", 53 | "time-span": "^5.1.0", 54 | "tsd": "^0.29.0", 55 | "xo": "^0.56.0" 56 | }, 57 | "xo": { 58 | "rules": { 59 | "n/prefer-global/process": "off", 60 | "n/prefer-global/buffer": "off" 61 | } 62 | }, 63 | "ava": { 64 | "workerThreads": false 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # make-asynchronous 2 | 3 | > Make a synchronous function asynchronous by running it in a [worker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) 4 | 5 | This makes it super simple to offload some expensive work without having to deal with the complex Web Workers API. 6 | 7 | **Please upvote [this Node.js issue](https://github.com/nodejs/node/issues/43583) 🙏** It would let us reduce the amount of dependencies and simplify the code. 8 | 9 | *Works in Node.js and browsers.* 10 | 11 | ## Install 12 | 13 | ```sh 14 | npm install make-asynchronous 15 | ``` 16 | 17 | ## Usage 18 | 19 | ```js 20 | import makeAsynchronous from 'make-asynchronous'; 21 | 22 | const fn = makeAsynchronous(number => { 23 | return performExpensiveOperation(number); 24 | }); 25 | 26 | console.log(await fn(2)); 27 | //=> 345342 28 | ``` 29 | 30 | ## API 31 | 32 | ### makeAsynchronous(function) 33 | 34 | Returns a wrapped version of the given function which executes asynchronously in a background thread (meaning it will not block the main thread). 35 | 36 | The given function is serialized, so you cannot use any variables or imports from outside the function scope. You can instead pass in arguments to the function. 37 | 38 | ### makeAsynchronousIterable(function) 39 | 40 | Make the iterable returned by a function asynchronous by running it in a worker. 41 | 42 | ```js 43 | import {makeAsynchronousIterable} from 'make-asynchronous'; 44 | 45 | const fn = makeAsynchronousIterable(function * (number) { 46 | yield * performExpensiveOperation(number); 47 | }); 48 | 49 | for await (const number of fn(2)) { 50 | console.log(number); 51 | } 52 | ``` 53 | 54 | #### fn.withSignal(signal) 55 | 56 | The function returned by `makeAsynchronous` and `makeAsynchronousIterable` has an additional method which allows an [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) to be provided. 57 | 58 | ```js 59 | import makeAsynchronous from 'make-asynchronous'; 60 | 61 | const fn = makeAsynchronous(number => { 62 | return performExpensiveOperation(number); 63 | }); 64 | 65 | const controller = new AbortController(); 66 | const timeoutId = setTimeout(() => { 67 | controller.abort(); 68 | }, 1000); // 1 second timeout 69 | 70 | const result = await fn.withSignal(controller.signal)(2); 71 | clearTimeout(timeoutId); 72 | 73 | console.log(result); 74 | //=> 345342 75 | ``` 76 | 77 | ## Related 78 | 79 | - [make-synchronous](https://github.com/sindresorhus/make-synchronous) - Make an asynchronous function synchronous 80 | - [sleep-synchronously](https://github.com/sindresorhus/sleep-synchronously) - Block the main thread for a given amount of time 81 | -------------------------------------------------------------------------------- /test.js: -------------------------------------------------------------------------------- 1 | import test from 'ava'; 2 | import timeSpan from 'time-span'; 3 | import inRange from 'in-range'; 4 | import makeAsynchronous, {makeAsynchronousIterable} from './index.js'; 5 | 6 | const abortError = new Error('Aborted'); 7 | 8 | test('main', async t => { 9 | const fixture = {x: '🦄'}; 10 | const end = timeSpan(); 11 | 12 | const result = await makeAsynchronous(fixture => { 13 | let x = '1'; 14 | 15 | while (true) { // eslint-disable-line no-constant-condition 16 | x += Math.random() < 0.5 ? Date.now().toString() : '0'; 17 | 18 | if (x >= 9_999_999_999_999) { 19 | break; 20 | } 21 | } 22 | 23 | return fixture; 24 | })(fixture); 25 | 26 | t.true(inRange(end(), {start: 10, end: 1000}), `${end()}`); 27 | t.deepEqual(result, fixture); 28 | }); 29 | 30 | test('with pre-aborted AbortSignal', async t => { 31 | const controller = new AbortController(); 32 | 33 | controller.abort(abortError); 34 | 35 | await t.throwsAsync(makeAsynchronous(() => { 36 | while (true) {} // eslint-disable-line no-constant-condition, no-empty 37 | }).withSignal(controller.signal), { 38 | message: abortError.message, 39 | }); 40 | }); 41 | 42 | test('with interrupting abortion of AbortSignal', async t => { 43 | const controller = new AbortController(); 44 | 45 | const promise = makeAsynchronous(() => { 46 | while (true) {} // eslint-disable-line no-constant-condition, no-empty 47 | }).withSignal(controller.signal)(); 48 | 49 | controller.abort(abortError); 50 | 51 | await t.throwsAsync(promise, { 52 | message: abortError.message, 53 | }); 54 | }); 55 | 56 | test('error', async t => { 57 | await t.throwsAsync( 58 | makeAsynchronous(() => { 59 | throw new TypeError('unicorn'); 60 | })(), 61 | { 62 | instanceOf: TypeError, 63 | message: 'unicorn', 64 | }, 65 | ); 66 | }); 67 | 68 | test.failing('dynamic import works', async t => { 69 | await t.notThrowsAsync( 70 | makeAsynchronous(async () => { 71 | await import('time-span'); 72 | })(), 73 | ); 74 | }); 75 | 76 | test('iterator object', async t => { 77 | const fixture = [1, 2]; 78 | 79 | const asyncIterable = makeAsynchronousIterable(fixture => fixture[Symbol.iterator]())(fixture); 80 | const result = []; 81 | 82 | for await (const value of asyncIterable) { 83 | result.push(value); 84 | } 85 | 86 | t.deepEqual(result, fixture); 87 | }); 88 | 89 | test('iterator object with pre-aborted AbortSignal', async t => { 90 | const controller = new AbortController(); 91 | 92 | controller.abort(abortError); 93 | 94 | const asyncIterable = makeAsynchronousIterable(function * () { // eslint-disable-line require-yield 95 | while (true) {} // eslint-disable-line no-constant-condition, no-empty 96 | }).withSignal(controller.signal)(); 97 | 98 | await t.throwsAsync(async () => { 99 | for await (const _ of asyncIterable) {} // eslint-disable-line no-unused-vars, no-empty 100 | }, { 101 | message: abortError.message, 102 | }); 103 | }); 104 | 105 | test('iterator object with interrupting abortion of AbortSignal', async t => { 106 | const controller = new AbortController(); 107 | 108 | const asyncIterable = makeAsynchronousIterable(function * () { // eslint-disable-line require-yield 109 | while (true) {} // eslint-disable-line no-constant-condition, no-empty 110 | }).withSignal(controller.signal)(); 111 | 112 | controller.abort(abortError); 113 | 114 | await t.throwsAsync(async () => { 115 | for await (const _ of asyncIterable) {} // eslint-disable-line no-unused-vars, no-empty 116 | }, { 117 | message: abortError.message, 118 | }); 119 | }); 120 | 121 | test('generator function', async t => { 122 | const fixture = [1, 2]; 123 | 124 | const asyncIterable = makeAsynchronousIterable(function * (fixture) { 125 | for (const value of fixture) { 126 | yield value; 127 | } 128 | })(fixture); 129 | 130 | const result = []; 131 | 132 | for await (const value of asyncIterable) { 133 | result.push(value); 134 | } 135 | 136 | t.deepEqual(result, fixture); 137 | }); 138 | 139 | test('generator function that throws', async t => { 140 | const fixture = [1, 2]; 141 | const errorMessage = 'Catch me if you can!'; 142 | 143 | const asyncIterable = makeAsynchronousIterable(function * (fixture, errorMessage) { 144 | for (const value of fixture) { 145 | yield value; 146 | } 147 | 148 | throw new Error(errorMessage); 149 | })(fixture, errorMessage); 150 | 151 | const result = []; 152 | 153 | await t.throwsAsync(async () => { 154 | for await (const value of asyncIterable) { 155 | result.push(value); 156 | } 157 | }, { 158 | message: errorMessage, 159 | }, 'error is propagated'); 160 | 161 | t.deepEqual(result, fixture); 162 | }); 163 | --------------------------------------------------------------------------------