Intro
一个类似 debounce
的高阶函数,但是接收一个异步任务。区别是在debounceAsync
里,如果任务没有执行则会返回一个always pending promise
。
A higher-order function like debounce
, but receiving an asynchronous task. The difference is that in debounceAsync
, an always pending promise
is returned if the task is not executed.
下面两段代码的运行效果是一样的,只是风格不同:
The following two pieces of code run the same way, just in different styles:
export default defineComponent({
setup() {
const suggestions = ref<string[]>([]);
return {
suggestions,
// 同步风格 Synchronization style
onInput: debounce(function onInput(e) {
const keywords = e.target.value;
searchApi(keywords).then((rez) => {
suggestions.value = rez;
});
}),
};
},
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const debouncedSearchApi = debounceAsync(searchApi);
export default defineComponent({
setup() {
const suggestions = ref<string[]>([]);
return {
suggestions,
// 异步风格 Asynchronous style
async onInput(e) {
// 注意在 `await debouncedSearchApi` 之前的代码仍会执行
// Note that the code before `await debouncedSearchApi` will still execute
const keywords = e.target.value;
// 会在适当的时机在此处卡住
// will get stuck here at the right time
const rez = await debouncedSearchApi(keywords);
suggestions.value = rez;
},
};
},
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Demo
Types
export declare function debounceAsync<T, P extends any[], R>(fn: (this: T, ...p: P) => Promise<R>, ms?: number): (this: T, ...p: P) => Promise<R>;
1