函数队列处理,可以同步处理和异步处理
//函数队列处理,可以同步处理和异步处理
function ArrayQueue() {
var arr = [];
var locker = false
let mode = 'sync'//async 异步 ,同步sync
//入队操作
this.push = async function (element) {
if (typeof element != "function")
{
throw new Error('进队列的必须是函数')
return
}
if (Object.prototype.toString.call(element) == '[object AsyncFunction]') {
arr.push(element);
}
if (Object.prototype.toString.call(element) == '[object Function]') {
arr.push(()=>{
return new Promise((resolve)=>{
element()
resolve()
})
})
}
if (!locker) {
while (arr.length) {
locker = true
if (typeof this.getFront() == "function") {
if (mode == 'async') {
this.getFront()()
}
if (mode == 'sync') {
await this.getFront()()
}
}
this.pop()
}
}
return true;
}
this.console = function () {
console.log(arr)
}
this.functionType = (v = 'async') => {
mode = v
}
//出队操作
this.pop = function () {
let res = arr.shift();
if (arr.length == 0) {
locker = false
}
return res;
}
//获取队首
this.getFront = function () {
return arr[0];
}
//获取队尾
this.getRear = function () {
return arr[arr.length - 1]
}
//清空队列
this.clear = function () {
arr = [];
}
//获取队长
this.size = function () {
return arr.length;
}
}
使用 方法例如
let queue = new ArrayQueue()
let a = () => {
console.log('a')
}
let b = () => {
console.log('b')
}
queue.push(a)
queue.push(a)
queue.push(a)
queue.push(b)
打印结果
队列实例声明之后,可以通过queue.functionType('async') 设置成异步,默认是同步,
同步就是逐个执行进队列的方法,异步就是队列直接执行所有方法,不进行上一个方法执行完再执行下一个