task-queue.uts
1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
export default class TaskQueue {
name: string
queue: Promise<any | null>
constructor(name: string = 'TaskQueue') {
this.name = name
this.queue = Promise.resolve(null)
}
/**
* 将任务加入队列
* @param {Function} task - 返回 Promise 的任务函数
* @param {number} timeout - 超时时间(ms),默认 20000
* @returns {Promise<any>}
*/
enqueue(task: () => Promise<any>, timeout: number = 20000): Promise<any | null> {
const taskWithTimeout = (): Promise<any | null> => this.withTimeout(task, timeout)
// 将任务追加到队列末尾
// 注意:在UTS中,Promise的类型需要明确,这里假设所有任务返回 Promise<any>
const next = this.queue.then((_: any | null): Promise<any | null> => {
return taskWithTimeout()
})
// 更新队列指针,确保队列始终指向最新的 Promise,且永远是 resolved 状态(catch 了错误)
this.queue = next.then((res: any | null): any | null => { return null }, (_: any): any | null => { return null })
return next
}
/**
* 带超时控制的任务执行器
*/
private withTimeout(task: () => Promise<any>, timeout: number): Promise<any | null> {
return new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
const error = new Error(`${this.name}操作超时(${timeout}ms)`)
// uni.$logger?.local?.error(error.message)
console.error(error.message)
reject(error)
}, timeout)
task().then((res: any | null) => {
clearTimeout(timeoutId)
resolve(res)
}, (err: any) => {
clearTimeout(timeoutId)
reject(err)
})
})
}
}