Skip to content

Commit

Permalink
BrowserInterface.chain correctness
Browse files Browse the repository at this point in the history
  • Loading branch information
ForsakenHarmony committed Jun 21, 2023
1 parent c71ace6 commit b6706d3
Showing 1 changed file with 22 additions and 20 deletions.
42 changes: 22 additions & 20 deletions test/lib/browsers/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,36 +11,38 @@ export type Event = 'request'
* You can manually await this interface to wait for completion of the last scheduled command.
*/
export abstract class BrowserInterface implements PromiseLike<any> {
private promise: any
then: PromiseLike<any>['then']
private catch: any
private promise?: Promise<any> = Promise.resolve()
then: Promise<any>['then'] = this.promise.then.bind(this.promise)
catch: Promise<any>['catch'] = this.promise.catch.bind(this.promise)
finally: Promise<any>['finally'] = this.promise.finally.bind(this.promise)

protected chain(nextCall: any): BrowserInterface {
if (!this.promise) {
this.promise = Promise.resolve(this)
protected chain<T>(
nextCall: (current: any) => T | PromiseLike<T>
): BrowserInterface & Promise<T> {
const promise = Promise.resolve(this.promise).then(nextCall)

function get(target: BrowserInterface, p: string | symbol): any {
switch (p) {
case 'promise':
return promise
default:
return target[p] ?? promise[p]
}
}
this.promise = this.promise.then(nextCall)
this.then = (...args) => this.promise.then(...args)
this.catch = (...args) => this.promise.catch(...args)
return this

return new Proxy<any>(this, {
get,
})
}

/**
* This function will run in chain - it will wait for previous commands.
* But it won't have an effect on chain value and chain will still be green if this throws.
*/
protected chainWithReturnValue<T>(
callback: (...args: any[]) => Promise<T>
callback: (value: any) => T | PromiseLike<T>
): Promise<T> {
return new Promise<T>((resolve, reject) => {
this.chain(async (...args: any[]) => {
try {
resolve(await callback(...args))
} catch (error) {
reject(error)
}
})
})
return Promise.resolve(this.promise).then(callback)
}

async setup(
Expand Down

0 comments on commit b6706d3

Please sign in to comment.