-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
博文
committed
Jun 30, 2021
1 parent
8b5840e
commit a4976c6
Showing
2 changed files
with
41 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,26 +1,37 @@ | ||
/** | ||
* @author bowencool<z.bowen66@gmail.com> | ||
* @description 异步节流:上一次的promise完成之前,不会再次触发。 | ||
* @param fn | ||
* @param {boolean} [config.useSamePromise] pending期间,使用同一个 Promise 作为结果 | ||
*/ | ||
export default function throttleAsync<T, P extends any[], R>( | ||
fn: (this: T, ...p: P) => Promise<R>, | ||
{ useSamePromise = false } = {}, | ||
) { | ||
let isPending = false; | ||
let theLastPromise: null | Promise<R> = null; | ||
return function asyncThrottled(this: T, ...args: P): Promise<R> { | ||
if (isPending) { | ||
if (useSamePromise && theLastPromise) { | ||
return theLastPromise; | ||
} | ||
return new Promise(() => {}); | ||
} else { | ||
isPending = true; | ||
return fn | ||
const ret = fn | ||
.call(this, ...args) | ||
.then((...a1) => { | ||
isPending = false; | ||
theLastPromise = null; | ||
return Promise.resolve(...a1); | ||
}) | ||
.catch((...a2) => { | ||
isPending = false; | ||
theLastPromise = null; | ||
return Promise.reject(...a2); | ||
}); | ||
theLastPromise = ret; | ||
isPending = true; | ||
return ret; | ||
} | ||
}; | ||
} |