-
Notifications
You must be signed in to change notification settings - Fork 22
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
84 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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') | ||
}) | ||
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |