Skip to content

Commit

Permalink
33 - fix use async
Browse files Browse the repository at this point in the history
  • Loading branch information
Daniel Schaffer committed Mar 1, 2019
1 parent f15ae54 commit f979e33
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 4 deletions.
1 change: 1 addition & 0 deletions packages/dandi/common/index.ts
Expand Up @@ -10,6 +10,7 @@ export * from './src/metadata'
export * from './src/method.target'
export * from './src/package.global.symbol'
export * from './src/primitive'
export * from './src/promise'
export * from './src/type.helpers'
export * from './src/url'
export * from './src/uuid'
10 changes: 6 additions & 4 deletions packages/dandi/common/src/disposable.ts
@@ -1,5 +1,6 @@
import { AppError } from './app.error'
import { globalSymbol } from './global.symbol'
import { isPromise } from './promise'

export type DisposeFn = (reason: string) => void

Expand Down Expand Up @@ -109,16 +110,17 @@ export class Disposable {
}

public static async useAsync<T extends Disposable, TResult = void>(
obj: T,
obj: T | Promise<T>,
use: (obj: T) => Promise<TResult>,
): Promise<TResult> {
const resolvedObj = isPromise(obj) ? await obj : obj
try {
return await use(obj)
return await use(resolvedObj)
} catch (err) {
throw err
} finally {
if (Disposable.isDisposable(obj)) {
await obj.dispose('after Disposable.useAsync()')
if (Disposable.isDisposable(resolvedObj)) {
await resolvedObj.dispose('after Disposable.useAsync()')
}
}
}
Expand Down
3 changes: 3 additions & 0 deletions packages/dandi/common/src/promise.ts
@@ -0,0 +1,3 @@
export function isPromise<T>(obj: any | Promise<T>): obj is Promise<T> {
return obj instanceof Promise || (obj && typeof obj.then === 'function')
}

0 comments on commit f979e33

Please sign in to comment.