Skip to content

Commit

Permalink
fix: exec multiple times error (#1680) (#1685)
Browse files Browse the repository at this point in the history
* fix: exec multiple times error

Co-authored-by: Hu Song <[email protected]>
  • Loading branch information
cptbtptpbcptdtptp and gz65555 authored Aug 3, 2023
1 parent 40bbff9 commit 12e57a2
Showing 1 changed file with 26 additions and 23 deletions.
49 changes: 26 additions & 23 deletions packages/core/src/asset/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,23 +35,12 @@ export function request<T>(url: string, config: RequestConfig = {}): AssetPromis
config.timeout = config.timeout ?? defaultTimeout;
config.type = config.type ?? getMimeTypeFromUrl(url);
const realRequest = config.type === "image" ? requestImage : requestRes;
let lastError: Error;
const executor = new MultiExecutor(
() => {
return realRequest<T>(url, config)
.onProgress(setProgress)
.then((res) => {
resolve(res);
executor.stop();
})
.catch((err) => (lastError = err));
},
() => realRequest<T>(url, config).onProgress(setProgress),
retryCount,
retryInterval
);
executor.start(() => {
reject(lastError);
});
executor.start().onError(reject).onComplete(resolve);
});
}

Expand Down Expand Up @@ -138,6 +127,9 @@ function getMimeTypeFromUrl(url: string) {
export class MultiExecutor {
private _timeoutId: number = -100;
private _currentCount = 0;
private _onComplete: Function;
private _onError: Function;
private _error: any;
constructor(
private execFunc: (count?: number) => Promise<any>,
private totalCount: number,
Expand All @@ -146,25 +138,36 @@ export class MultiExecutor {
this.exec = this.exec.bind(this);
}

private done: Function;
start(done?: Function): void {
this.done = done;
start() {
this.exec();
return this;
}

stop(): void {
clearTimeout(this._timeoutId);
onComplete(func: Function) {
this._onComplete = func;
return this;
}

onError(func: Function) {
this._onError = func;
return this;
}

cancel() {
window.clearTimeout(this._timeoutId);
}

private exec(): void {
if (this._currentCount >= this.totalCount) {
this.done && this.done();
this._onError && this._onError(this._error);
return;
}
this._currentCount++;
this.execFunc(this._currentCount).then(() => {
//@ts-ignore
this._timeoutId = setTimeout(this.exec, this.interval);
});
this.execFunc(this._currentCount)
.then((result) => this._onComplete && this._onComplete(result))
.catch((e) => {
this._error = e;
this._timeoutId = window.setTimeout(this.exec, this.interval);
});
}
}

0 comments on commit 12e57a2

Please sign in to comment.