异步队列util/asyncQueue
统一管理异步任务,确保所有异步任务有序执行。
基本用法
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
AsyncQueue
和 Promise
都用于解决异步任务并发的问题。
但它们解决问题的思路不同:
Promise
类似多米诺骨牌。
每个 Promise
对象都有一个状态,当 Promise
对象状态切换为已完成后,
它将执行所有通过 then()
添加的回调函数,并将状态传递给下一个 Promise
对象,
以此确保所有回调函数都是按顺序执行的。
AsyncQueue
类似排队。
AsyncQueue
统一管理了队列内所有回调函数并一一通知执行。
如果程序中只需确保函数的执行顺序,建议使用更灵活的 Promise
。
如果程序需要人工干预等待列表(如插队执行),需要使用 AsyncQueue
。
AsyncQueue
和 Promise
对象可以互相转换:
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. 继承自
|
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:
添加一个任务函数。
返回值类型: |
添加一个任务函数。 |
— | ||||||||||||||||||||||||||||||||||||||
⮞
skip()():
终止当前正在执行的异步任务并执行其它正在等待的任务。 返回值类型: |
终止当前正在执行的异步任务并执行其它正在等待的任务。 |
— | ||||||||||||||||||||||||||||||||||||||
⮞
suspend(...)(abortable?:
|
挂起当前队列。所有后续任务都将开始等待。 |
— | ||||||||||||||||||||||||||||||||||||||
⮞
resume(...)(data?:
通知当前异步任务已经完成,并继续执行下一个任务。
返回值类型: |
通知当前异步任务已经完成,并继续执行下一个任务。 |
— | ||||||||||||||||||||||||||||||||||||||
⮞
includes(searchElement, ...)(searchElement:
Determines whether an array includes a certain element, returning true or false as appropriate.
返回值类型: 继承自
|
Determines whether an array includes a certain element, returning true or false as appropriate. |
Array<T> |
||||||||||||||||||||||||||||||||||||||
⮞
toString()():
Returns a string representation of an array. 返回值类型: 继承自
|
Returns a string representation of an array. |
Array<T> |
||||||||||||||||||||||||||||||||||||||
⮞
toLocaleString()():
Returns a string representation of an array. The elements are converted to string using thier toLocalString methods. 返回值类型: 继承自
|
Returns a string representation of an array. The elements are converted to string using thier toLocalString methods. |
Array<T> |
||||||||||||||||||||||||||||||||||||||
⮞
push(...)(...items:
Appends new elements to an array, and returns the new length of the array.
返回值类型: 继承自
|
Appends new elements to an array, and returns the new length of the array. |
Array<T> |
||||||||||||||||||||||||||||||||||||||
⮞
pop()():
Removes the last element from an array and returns it. 返回值类型: 继承自
|
Removes the last element from an array and returns it. |
Array<T> |
||||||||||||||||||||||||||||||||||||||
⮞
concat(...)(...items:
Combines two or more arrays.
返回值类型: Combines two or more arrays.
返回值类型: 继承自
|
Combines two or more arrays. |
Array<T> |
||||||||||||||||||||||||||||||||||||||
⮞
join(...)(separator?:
Adds all the elements of an array separated by the specified separator string.
返回值类型: 继承自
|
Adds all the elements of an array separated by the specified separator string. |
Array<T> |
||||||||||||||||||||||||||||||||||||||
⮞
reverse()():
Reverses the elements in an Array. 返回值类型: 继承自
|
Reverses the elements in an Array. |
Array<T> |
||||||||||||||||||||||||||||||||||||||
⮞
shift()():
Removes the first element from an array and returns it. 返回值类型: 继承自
|
Removes the first element from an array and returns it. |
Array<T> |
||||||||||||||||||||||||||||||||||||||
⮞
slice(...)(start?:
Returns a section of an array.
返回值类型: 继承自
|
Returns a section of an array. |
Array<T> |
||||||||||||||||||||||||||||||||||||||
⮞
sort(...)(compareFn?:
Sorts an array.
返回值类型: 继承自
|
Sorts an array. |
Array<T> |
||||||||||||||||||||||||||||||||||||||
⮞
splice(start, ...)(start:
Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.
返回值类型: Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.
返回值类型: 继承自
|
Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. |
Array<T> |
||||||||||||||||||||||||||||||||||||||
⮞
unshift(...)(...items:
Inserts new elements at the start of an array.
返回值类型: 继承自
|
Inserts new elements at the start of an array. |
Array<T> |
||||||||||||||||||||||||||||||||||||||
⮞
indexOf(searchElement, ...)(searchElement:
Returns the index of the first occurrence of a value in an array.
返回值类型: 继承自
|
Returns the index of the first occurrence of a value in an array. |
Array<T> |
||||||||||||||||||||||||||||||||||||||
⮞
lastIndexOf(searchElement, ...)(searchElement:
Returns the index of the last occurrence of a specified value in an array.
返回值类型: 继承自
|
Returns the index of the last occurrence of a specified value in an array. |
Array<T> |
||||||||||||||||||||||||||||||||||||||
⮞
every(callbackfn, ...)(callbackfn:
Determines whether all the members of an array satisfy the specified test.
返回值类型: 继承自
|
Determines whether all the members of an array satisfy the specified test. |
Array<T> |
||||||||||||||||||||||||||||||||||||||
⮞
some(callbackfn, ...)(callbackfn:
Determines whether the specified callback function returns true for any element of an array.
返回值类型: 继承自
|
Determines whether the specified callback function returns true for any element of an array. |
Array<T> |
||||||||||||||||||||||||||||||||||||||
⮞
forEach(callbackfn, ...)(callbackfn:
Performs the specified action for each element in an array.
返回值类型: 继承自
|
Performs the specified action for each element in an array. |
Array<T> |
||||||||||||||||||||||||||||||||||||||
⮞
map(callbackfn, ...)<U>(callbackfn:
Calls a defined callback function on each element of an array, and returns an array that contains the results.
返回值类型: 继承自
|
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:
Returns the elements of an array that meet the condition specified in a callback function.
返回值类型: Returns the elements of an array that meet the condition specified in a callback function.
返回值类型: 继承自
|
Returns the elements of an array that meet the condition specified in a callback function. |
Array<T> |
||||||||||||||||||||||||||||||||||||||
⮞
reduce(callbackfn)(callbackfn:
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.
返回值类型:
返回值类型: 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.
返回值类型: 继承自
|
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:
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.
返回值类型:
返回值类型: 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.
返回值类型: 继承自
|
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]()():
Returns an object whose properties have the value 'true' when they will be absent when used in a 'with' statement. 返回值类型: 继承自
|
Returns an object whose properties have the value 'true' when they will be absent when used in a 'with' statement. |
Array<T> |
||||||||||||||||||||||||||||||||||||||
⮞
[Symbol.iterator]()():
Iterator 返回值类型: 继承自
|
Iterator |
Array<T> |
||||||||||||||||||||||||||||||||||||||
⮞
entries()():
Returns an iterable of key, value pairs for every entry in the array 返回值类型: 继承自
|
Returns an iterable of key, value pairs for every entry in the array |
Array<T> |
||||||||||||||||||||||||||||||||||||||
⮞
keys()():
Returns an iterable of keys in the array 返回值类型: 继承自
|
Returns an iterable of keys in the array |
Array<T> |
||||||||||||||||||||||||||||||||||||||
⮞
values()():
Returns an iterable of values in the array 返回值类型: 继承自
|
Returns an iterable of values in the array |
Array<T> |
||||||||||||||||||||||||||||||||||||||
⮞
find(predicate, ...)<S>(predicate:
Returns the value of the first element in the array where predicate is true, and undefined otherwise.
返回值类型:
返回值类型: 继承自
|
Returns the value of the first element in the array where predicate is true, and undefined otherwise. |
Array<T> |
||||||||||||||||||||||||||||||||||||||
⮞
findIndex(predicate, ...)(predicate:
Returns the index of the first element in the array where predicate is true, and -1 otherwise.
返回值类型: 继承自
|
Returns the index of the first element in the array where predicate is true, and -1 otherwise. |
Array<T> |
||||||||||||||||||||||||||||||||||||||
⮞
fill(value, ...)(value:
Returns the this object after filling the section identified by start and end with value
返回值类型: 继承自
|
Returns the this object after filling the section identified by start and end with value |
Array<T> |
||||||||||||||||||||||||||||||||||||||
⮞
copyWithin(target, start, ...)(target:
Returns the this object after copying a section of the array identified by start and end to the same array starting at position target
返回值类型: 继承自
|
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()():
终止当前异步操作。 返回值类型: |
终止当前异步操作。 |