Skip to content

Commit

Permalink
fix(signal): 多个初始 get 表现正常
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Nov 17, 2021
1 parent 29dde36 commit ac4d063
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 12 deletions.
15 changes: 15 additions & 0 deletions src/utils/signal.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,19 @@ describe('signal', () => {
userData.throw('err')
await expect(userData.get()).rejects.toContain('err')
})

test('多个初始 get 表现正常', async () => {
let _userData = ''
let _userData2 = ''
const userData = signal<string>()
userData.get().then(v => (_userData = v))
userData.get().then(v => (_userData2 = v))
await wait(0)
expect(_userData).toBe('')
expect(_userData2).toBe('')
userData.set('test')
await wait(0)
expect(_userData).toBe('test')
expect(_userData2).toBe('test')
})
})
24 changes: 12 additions & 12 deletions src/utils/signal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,26 +14,26 @@ export function signal<T>(): SignalResult<T> {
let error!: any
let isException = false

let $resolve: any
let $reject: any
const $resolve: any[] = []
const $reject: any[] = []

const setValue: SignalResult<T>['set'] = _value => {
value = _value
if ($resolve) {
$resolve(value)
$resolve = null
$reject = null
if ($resolve.length) {
$resolve.forEach(resolve => resolve(value))
$resolve.length = 0
$reject.length = 0
}
isOk = true
isException = false
}

const throwError: SignalResult<T>['throw'] = _error => {
error = _error
if ($reject) {
$reject(error)
$resolve = null
$reject = null
if ($reject.length) {
$reject.forEach(reject => reject(error))
$resolve.length = 0
$reject.length = 0
}
isOk = false
isException = true
Expand All @@ -53,8 +53,8 @@ export function signal<T>(): SignalResult<T> {
if (isException) {
return reject(error)
}
$resolve = resolve
$reject = reject
$resolve.push(resolve)
$reject.push(reject)
})
}

Expand Down

0 comments on commit ac4d063

Please sign in to comment.