Skip to content

Commit

Permalink
feat(utils): 新增 signal
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Nov 2, 2021
1 parent b10e2b4 commit d4df232
Show file tree
Hide file tree
Showing 3 changed files with 84 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ export * from './run'
export * from './sampleBy'
export * from './sampleIndex'
export * from './selectDom'
export * from './signal'
export * from './swap'
export * from './traverse'
export * from './TreeData'
Expand Down
37 changes: 37 additions & 0 deletions src/utils/signal.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { signal } from './signal'
import { wait } from './wait'

describe('signal', () => {
test('resolve', async () => {
let x = 0
const s = signal<number>()
s.then(_x => (x = _x))
expect(x).toBe(0)
s.resolve(2)
await wait(0)
expect(x).toBe(2)

// 只会触发一次 Promise
s.resolve(22)
await wait(0)
expect(x).toBe(2)
})

test('reject', async () => {
const x = 0
let err = ''
const s = signal<number>()
s.catch(_err => (err = _err))
expect(x).toBe(0)
expect(err).toBe('')
s.reject('err')
await wait(0)
expect(x).toBe(0)
expect(err).toBe('err')

// 只会触发一次 Promise
s.reject('err2')
await wait(0)
expect(err).toBe('err')
})
})
46 changes: 46 additions & 0 deletions src/utils/signal.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/**
* 信号。
*/
export function signal<T>(): Promise<T> & {
resolve: (value: T) => void
reject: (err: any) => void
} {
let _resolve: any
let _reject: any

let resolved = false
let resolvedValue: any
const resolve = (value: any) => {
if (!resolved) {
resolved = true
resolvedValue = value
_resolve?.(value)
}
}

let rejected = false
let rejectedValue: any
const reject = (value: any) => {
if (!rejected) {
rejected = true
rejectedValue = value
_reject?.(value)
}
}

const s: any = new Promise(($resolve, $reject) => {
if (resolved) {
$resolve(resolvedValue)
} else if (rejected) {
$reject(rejectedValue)
} else {
_resolve = $resolve
_reject = $reject
}
})

s.resolve = resolve
s.reject = reject

return s
}

0 comments on commit d4df232

Please sign in to comment.