use-worker-like-request
TypeScript icon, indicating that this package has built-in type declarations

0.2.0 • Public • Published

use-worker-like-request

npm version npm downloads

online demo

Pay attention: Not use it now, I had trouble with vitest to test web worker, when it solved, I will add tests to this library, and add some features.

Install

pnpm i use-worker-like-request

Usage

import { exportWorker } from "use-worker-like-request";

function fibonacci(n: number): number {
    if (n === 1) {
        return 1
    }

    if (n === 2) {
        return 2
    }

    return fibonacci(n - 1) + fibonacci(n - 2)
}

export default exportWorker(fibonacci);
import React from 'react'
import { useState } from 'react'
import useWorker from 'use-worker-like-request'
import reactLogo from './assets/react.svg'
import './App.css'
import fibonacci from './fibonacci'

const createWorker = () => new Worker(new URL('./fibonacci', import.meta.url), {
  type: 'module'
})

function App() {
  const [count, setCount] = useState(0)

  const {workerRunner, workerController} = useWorker<typeof fibonacci>(createWorker)

  async function handleClick() {
    console.log(await workerRunner(10))
  }

  return (
    <div className="App">
      <div>hello world</div>
      <button onClick={handleClick}>compute</button>
    </div>
  )
}

export default App

useWorker accept second parameter, it can auto terminate when your worker finished (success or fail).

const {
    workerRunner, 
    workerController
} = useWorker<typeof fibonacci>(createWorker, {autoTerminate: true})

And you can manual terminate:

workerController.killWorker()

You can show worker status by reading workerController.workerStatus, Its value will be one of :

export enum WORKER_STATUS {
    PENDING = 'PENDING',
    RUNNING = 'RUNNING',
    SUCCESS = 'SUCCESS',
    ERROR = 'ERROR',
}

Preview

pnpm example

Package Sidebar

Install

npm i use-worker-like-request

Weekly Downloads

2

Version

0.2.0

License

ISC

Unpacked Size

152 kB

Total Files

30

Last publish

Collaborators

  • mysteryzzz