Skip to content

Commit

Permalink
simplify fetcher's fetchPromise assignment
Browse files Browse the repository at this point in the history
  • Loading branch information
g11tech committed Oct 26, 2023
1 parent ca81ff0 commit fab73aa
Showing 1 changed file with 32 additions and 31 deletions.
63 changes: 32 additions & 31 deletions packages/client/src/sync/fetcher/fetcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -481,42 +481,43 @@ export abstract class Fetcher<JobTask, JobResult, StorageItem> extends Readable
/**
* Run the fetcher. Returns a promise that resolves once all tasks are completed.
*/
async _fetch() {
try {
this.write()
this.running = true
this.nextTasks()

while (this.running) {
if (this.next() === false) {
if (this.finished === this.total && this.destroyWhenDone) {
this.push(null)
}
await this.wait()
}
}
this.running = false
if (this.destroyWhenDone) {
this.destroy()
this.writer = null
}
if (this.syncErrored) throw this.syncErrored
return true
} finally {
this.fetchPromise = null
}
}

/**
* Wraps the internal fetcher to track its promise
*/
async fetch() {
if (this.running) {
return false
}

this.fetchPromise = new Promise(
// wrapped in try catch to make sure no unhandled exception is thrown so we can
// ignore eslint error
// eslint-disable-next-line no-async-promise-executor
async (resolve, reject) => {
try {
this.write()
this.running = true
this.nextTasks()

while (this.running) {
if (this.next() === false) {
if (this.finished === this.total && this.destroyWhenDone) {
this.push(null)
}
await this.wait()
}
}
this.running = false
if (this.destroyWhenDone) {
this.destroy()
this.writer = null
}
if (this.syncErrored) throw this.syncErrored
this.fetchPromise = null
resolve(true)
} catch (e) {
reject(e)
}
}
)
if (this.fetchPromise === null) {
this.fetchPromise = this._fetch()
}
return this.fetchPromise
}

Expand Down

0 comments on commit fab73aa

Please sign in to comment.