Skip to content

Commit

Permalink
feat(Disposer): API 优化
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed May 30, 2019
1 parent 88daef3 commit e083763
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 20 deletions.
8 changes: 7 additions & 1 deletion src/Disposer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,13 @@ test('表现正常', async () => {

disposer.add(dispose1)
disposer.add(dispose1)
disposer.add(dispose2, dispose3)
disposer.add([dispose2, dispose3, dispose1])

await disposer.dispose()

expect(dispose1).toBeCalledTimes(1)
expect(dispose2).toBeCalledTimes(1)
expect(dispose3).toBeCalledTimes(1)

await disposer.dispose()

Expand Down
27 changes: 8 additions & 19 deletions src/Disposer.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { isPromiseLike } from './is'
import { castArray } from './castArray'
import { parallel } from './parallel'

/**
* 待释放项目。
Expand All @@ -17,10 +18,10 @@ export class Disposer {
/**
* 新增待释放项目。
*
* @param items 待释放项目的序列
* @param item 待释放项目
*/
add(...items: DisposerItem[]) {
items.forEach(item => {
add(item: DisposerItem | DisposerItem[]) {
castArray(item).forEach(item => {
if (this.jar.indexOf(item) === -1) {
this.jar.push(item)
}
Expand All @@ -31,20 +32,8 @@ export class Disposer {
* 释放所有项目。
*/
dispose() {
return (
Promise
.all(
this.jar.map(item => {
const result = item()
if (isPromiseLike(result)) {
return result
}
return Promise.resolve()
}),
)
.then(() => {
this.jar = []
})
)
return parallel(this.jar).then(() => {
this.jar = []
})
}
}

0 comments on commit e083763

Please sign in to comment.