Teal TealUI

异步队列util/asyncQueue

统一管理异步任务,确保所有异步任务有序执行。

基本用法
传递数据
插队
AsyncQueue vs Promise
API
AsyncQueue 类
Abortable 接口

基本用法

AsyncQueue 就像是一个密室,每个任务函数都可以通过 then() 按顺序进入密室执行。

import AsyncQueue from "util/asyncQueue";

var deferred = new AsyncQueue();    // 创建新的异步队列。

deferred.then(() => {               // 添加一个任务。
    console.log("A");
});

deferred.then(() => {               // 再添加一个任务。这个任务会等待上个任务。
    console.log("B");
});

deferred.then(() => {               // 再添加一个任务。这个任务会等待上个任务。
    console.log("C");
});

正在执行的函数可以通过 suspend() 关上密室的门,这时其它任务函数都会进入等待状态。 当函数通过 resume() 打开密室的门后,下一个任务函数再进入密室执行。

import AsyncQueue from "util/asyncQueue";

var deferred = new AsyncQueue();

deferred.then(() => {
    console.log("A");
});

deferred.then(() => {
    console.log("B");
    deferred.suspend();             // 挂起队列,其它任务将开始等待。
    setTimeout(() => { 
        deferred.resume();          // 1 秒后:恢复队列,即执行下一个任务。
    }, 1000);
});

deferred.then(() => {
    console.log("C");
});

传递数据

上一个任务函数可通过 resume() 传递一个数据给下一个任务函数。

import AsyncQueue from "util/asyncQueue";

var deferred = new AsyncQueue();

deferred.then(() => {
    console.log("A");
});

deferred.then(() => {
    console.log("B");
    deferred.suspend();
    setTimeout(() => { 
        deferred.resume(1);         // 传递数据 1。
    }, 1000);
});

deferred.then(data => {
    console.log("C", data);         // 此处 data 为 1。
});

插队

除了让新任务等待当前正在执行的任务,还可以通过 then()第二参数让新任务插队执行。

比如现在正在执行将方块从 A 点移动到 B 点的动画, 如果此时需求改成从 A 点移动到 C 点,那么应该立即终止 A 点移动到 B 点的动画转而移向 C 点。

被插队的任务可能会被强制终止执行。 但不是所有任务都能强制终止的,如果一个任务希望支持强制终止,必须在 suspend() 传递一个对象,可通过调用其 abort() 方法来强制终止任务。

<button onclick="move(box, -offset.value)">左移</button>
<input type="number" id="offset" value="200" style="width: 6rem;">
<button onclick="move(box, +offset.value)">右移</button>
<div id="box" class="doc-box" style="position: relative; left: 300px;"></div>
<script>
    import AsyncQueue from "util/asyncQueue";

    var deferred = new AsyncQueue();

    export function move(box, delta) {
        var y = parseInt(box.style.left) + delta;           // 计算最终位置。

        deferred.then(() => {
            deferred.suspend({                              // 挂起队列,避免方块同时执行多个动画函数。
                abort(){                                    // 提供一个对象,使得当前动画可被终止。
                    clearInterval(timer);
                    deferred.resume();
                }
            });

            var current = parseInt(box.style.left);         // 计算初始位置。
            var timer = setInterval(() => {                 
                if (current < y) {                          // 移动方块,每次移动 1 像素。
                    current++;
                } else {
                    current--;
                }
                if (current == y) {                         // 已经移到最终位置,停止动画。
                    clearInterval(timer);
                    deferred.resume();
                } else {
                    box.style.left = current + "px";
                }
            }, 20);
        }, "abort");                                        // 如果在动画期间用户又设置了新终点,则需要终止当前的动画。

        deferred.then(() => {
            box.className += " doc-box-blue";
        });
    }
</script>

AsyncQueue vs Promise

AsyncQueuePromise 都用于解决异步任务并发的问题。

但它们解决问题的思路不同:

Promise 类似多米诺骨牌。 每个 Promise 对象都有一个状态,当 Promise 对象状态切换为已完成后, 它将执行所有通过 then() 添加的回调函数,并将状态传递给下一个 Promise 对象, 以此确保所有回调函数都是按顺序执行的。

AsyncQueue 类似排队。 AsyncQueue 统一管理了队列内所有回调函数并一一通知执行。

如果程序中只需确保函数的执行顺序,建议使用更灵活的 Promise。 如果程序需要人工干预等待列表(如插队执行),需要使用 AsyncQueue

AsyncQueuePromise 对象可以互相转换:

function asyncQueueToPromise(asyncQueue) { 
    return new Promise(resolve => {
        asyncQueue.then(resolve);
    });
}

function promiseToAsyncQueue(promise) {
    const asyncQueue = new AsyncQueue();
    asyncQueue.suspend();
    promise.then(() => {
        asyncQueue.resume();
    });
    return asyncQueue;
}

API

AsyncQueue 类

继承自:Function[]

表示一个异步任务队列。

字段 类型 描述 继承自
suspended : boolean

(只读)判断当前队列是否已被阻止。

boolean

(只读)判断当前队列是否已被阻止。

length : number

Gets or sets the length of the array. This is a number one higher than the highest element defined in an array.

继承自

Array<T>

number

Gets or sets the length of the array. This is a number one higher than the highest element defined in an array.

Array<T>
方法 描述 继承自
then(callback, ...)(callback:function, link?:string):void

添加一个任务函数。

参数 类型 描述 默认值
callback* (data: any) => void
link "wait" | "abort" | "insert" | "replace" | "cancel" "wait"

返回值

类型:void

添加一个任务函数。

skip()():void

终止当前正在执行的异步任务并执行其它正在等待的任务。

返回值

类型:void

终止当前正在执行的异步任务并执行其它正在等待的任务。

suspend(...)(abortable?:Abortable):void

挂起当前队列。所有后续任务都将开始等待。

参数 类型 描述 默认值
abortable Abortable

返回值

类型:void

挂起当前队列。所有后续任务都将开始等待。

resume(...)(data?:any):void

通知当前异步任务已经完成,并继续执行下一个任务。

参数 类型 描述 默认值
data any

返回值

类型:void

通知当前异步任务已经完成,并继续执行下一个任务。

includes(searchElement, ...)(searchElement:T, fromIndex?:number):boolean

Determines whether an array includes a certain element, returning true or false as appropriate.

参数 类型 描述 默认值
searchElement* T
fromIndex number

返回值

类型:boolean

继承自

Array<T>

Determines whether an array includes a certain element, returning true or false as appropriate.

Array<T>
toString()():string

Returns a string representation of an array.

返回值

类型:string

继承自

Array<T>

Returns a string representation of an array.

Array<T>
toLocaleString()():string

Returns a string representation of an array. The elements are converted to string using thier toLocalString methods.

返回值

类型:string

继承自

Array<T>

Returns a string representation of an array. The elements are converted to string using thier toLocalString methods.

Array<T>
push(...)(...items:T[]):number

Appends new elements to an array, and returns the new length of the array.

参数 类型 描述 默认值
items T[]

返回值

类型:number

继承自

Array<T>

Appends new elements to an array, and returns the new length of the array.

Array<T>
pop()():T

Removes the last element from an array and returns it.

返回值

类型:T

继承自

Array<T>

Removes the last element from an array and returns it.

Array<T>
concat(...)(...items:ReadonlyArray<T>[]):T[](2 重载)

Combines two or more arrays.

参数 类型 描述 默认值
items ReadonlyArray<T>[]

返回值

类型:T[]


Combines two or more arrays.

参数 类型 描述 默认值
items (T | ReadonlyArray<T>)[]

返回值

类型:T[]

继承自

Array<T>

Combines two or more arrays.

Array<T>
join(...)(separator?:string):string

Adds all the elements of an array separated by the specified separator string.

参数 类型 描述 默认值
separator string

返回值

类型:string

继承自

Array<T>

Adds all the elements of an array separated by the specified separator string.

Array<T>
reverse()():T[]

Reverses the elements in an Array.

返回值

类型:T[]

继承自

Array<T>

Reverses the elements in an Array.

Array<T>
shift()():T

Removes the first element from an array and returns it.

返回值

类型:T

继承自

Array<T>

Removes the first element from an array and returns it.

Array<T>
slice(...)(start?:number, end?:number):T[]

Returns a section of an array.

参数 类型 描述 默认值
start number
end number

返回值

类型:T[]

继承自

Array<T>

Returns a section of an array.

Array<T>
sort(...)(compareFn?:function):this

Sorts an array.

参数 类型 描述 默认值
compareFn (a: T, b: T) => number

返回值

类型:this

继承自

Array<T>

Sorts an array.

Array<T>
splice(start, ...)(start:number, deleteCount?:number):T[](2 重载)

Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.

参数 类型 描述 默认值
start* number
deleteCount number

返回值

类型:T[]


Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.

参数 类型 描述 默认值
start* number
deleteCount* number
items T[]

返回值

类型:T[]

继承自

Array<T>

Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.

Array<T>
unshift(...)(...items:T[]):number

Inserts new elements at the start of an array.

参数 类型 描述 默认值
items T[]

返回值

类型:number

继承自

Array<T>

Inserts new elements at the start of an array.

Array<T>
indexOf(searchElement, ...)(searchElement:T, fromIndex?:number):number

Returns the index of the first occurrence of a value in an array.

参数 类型 描述 默认值
searchElement* T
fromIndex number

返回值

类型:number

继承自

Array<T>

Returns the index of the first occurrence of a value in an array.

Array<T>
lastIndexOf(searchElement, ...)(searchElement:T, fromIndex?:number):number

Returns the index of the last occurrence of a specified value in an array.

参数 类型 描述 默认值
searchElement* T
fromIndex number

返回值

类型:number

继承自

Array<T>

Returns the index of the last occurrence of a specified value in an array.

Array<T>
every(callbackfn, ...)(callbackfn:function, thisArg?:any):boolean

Determines whether all the members of an array satisfy the specified test.

参数 类型 描述 默认值
callbackfn* (value: T, index: number, array: T[]) => boolean
thisArg any

返回值

类型:boolean

继承自

Array<T>

Determines whether all the members of an array satisfy the specified test.

Array<T>
some(callbackfn, ...)(callbackfn:function, thisArg?:any):boolean

Determines whether the specified callback function returns true for any element of an array.

参数 类型 描述 默认值
callbackfn* (value: T, index: number, array: T[]) => boolean
thisArg any

返回值

类型:boolean

继承自

Array<T>

Determines whether the specified callback function returns true for any element of an array.

Array<T>
forEach(callbackfn, ...)(callbackfn:function, thisArg?:any):void

Performs the specified action for each element in an array.

参数 类型 描述 默认值
callbackfn* (value: T, index: number, array: T[]) => void
thisArg any

返回值

类型:void

继承自

Array<T>

Performs the specified action for each element in an array.

Array<T>
map(callbackfn, ...)<U>(callbackfn:function, thisArg?:any):U[]

Calls a defined callback function on each element of an array, and returns an array that contains the results.

泛型参数 约束类型 默认类型
U
参数 类型 描述 默认值
callbackfn* (value: T, index: number, array: T[]) => U
thisArg any

返回值

类型:U[]

继承自

Array<T>

Calls a defined callback function on each element of an array, and returns an array that contains the results.

Array<T>
filter(callbackfn, ...)<S>(callbackfn:function, thisArg?:any):S[](2 重载)

Returns the elements of an array that meet the condition specified in a callback function.

泛型参数 约束类型 默认类型
S
参数 类型 描述 默认值
callbackfn* (value: T, index: number, array: T[]) => value is S
thisArg any

返回值

类型:S[]


Returns the elements of an array that meet the condition specified in a callback function.

参数 类型 描述 默认值
callbackfn* (value: T, index: number, array: T[]) => any
thisArg any

返回值

类型:T[]

继承自

Array<T>

Returns the elements of an array that meet the condition specified in a callback function.

Array<T>
reduce(callbackfn)(callbackfn:function):T(3 重载)

Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

参数 类型 描述 默认值
callbackfn* (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T

返回值

类型:T


参数 类型 描述 默认值
callbackfn* (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T
initialValue* T

返回值

类型:T


Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

泛型参数 约束类型 默认类型
U
参数 类型 描述 默认值
callbackfn* (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U
initialValue* U

返回值

类型:U

继承自

Array<T>

Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

Array<T>
reduceRight(callbackfn)(callbackfn:function):T(3 重载)

Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

参数 类型 描述 默认值
callbackfn* (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T

返回值

类型:T


参数 类型 描述 默认值
callbackfn* (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T
initialValue* T

返回值

类型:T


Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

泛型参数 约束类型 默认类型
U
参数 类型 描述 默认值
callbackfn* (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U
initialValue* U

返回值

类型:U

继承自

Array<T>

Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

Array<T>
[Symbol.unscopables]()():object

Returns an object whose properties have the value 'true' when they will be absent when used in a 'with' statement.

返回值

类型:{ copyWithin: boolean; entries: boolean; fill: boolean; find: boolean; findIndex: boolean; keys: boolean; values: boolean; }

继承自

Array<T>

Returns an object whose properties have the value 'true' when they will be absent when used in a 'with' statement.

Array<T>
[Symbol.iterator]()():IterableIterator<T>

Iterator

返回值

类型:IterableIterator<T>

继承自

Array<T>

Iterator

Array<T>
entries()():IterableIterator<[number, T]>

Returns an iterable of key, value pairs for every entry in the array

返回值

类型:IterableIterator<[number, T]>

继承自

Array<T>

Returns an iterable of key, value pairs for every entry in the array

Array<T>
keys()():IterableIterator<number>

Returns an iterable of keys in the array

返回值

类型:IterableIterator<number>

继承自

Array<T>

Returns an iterable of keys in the array

Array<T>
values()():IterableIterator<T>

Returns an iterable of values in the array

返回值

类型:IterableIterator<T>

继承自

Array<T>

Returns an iterable of values in the array

Array<T>
find(predicate, ...)<S>(predicate:function, thisArg?:any):S(2 重载)

Returns the value of the first element in the array where predicate is true, and undefined otherwise.

泛型参数 约束类型 默认类型
S
参数 类型 描述 默认值
predicate* (this: void, value: T, index: number, obj: T[]) => value is S
thisArg any

返回值

类型:S


参数 类型 描述 默认值
predicate* (value: T, index: number, obj: T[]) => boolean
thisArg any

返回值

类型:T

继承自

Array<T>

Returns the value of the first element in the array where predicate is true, and undefined otherwise.

Array<T>
findIndex(predicate, ...)(predicate:function, thisArg?:any):number

Returns the index of the first element in the array where predicate is true, and -1 otherwise.

参数 类型 描述 默认值
predicate* (value: T, index: number, obj: T[]) => boolean
thisArg any

返回值

类型:number

继承自

Array<T>

Returns the index of the first element in the array where predicate is true, and -1 otherwise.

Array<T>
fill(value, ...)(value:T, start?:number, end?:number):this

Returns the this object after filling the section identified by start and end with value

参数 类型 描述 默认值
value* T
start number
end number

返回值

类型:this

继承自

Array<T>

Returns the this object after filling the section identified by start and end with value

Array<T>
copyWithin(target, start, ...)(target:number, start:number, end?:number):this

Returns the this object after copying a section of the array identified by start and end to the same array starting at position target

参数 类型 描述 默认值
target* number
start* number
end number

返回值

类型:this

继承自

Array<T>

Returns the this object after copying a section of the array identified by start and end to the same array starting at position target

Array<T>

Abortable 接口

表示一个可终止的异步操作。

方法 描述
abort()():void

终止当前异步操作。

返回值

类型:void

终止当前异步操作。