任务调动
异步并行
几个异步同时执行,最后一个执行完毕调用一下回调方法
- 原生JavaScript
当多个任务要串行执行,结果要统一处理时,将多个任务放入队列中执行,直到所有任务结束才结束,一分钟执行60次
var mQueue = function () {this.fnSources = [];this.excuting = false;this.add = function (fn) {if (typeof fn !== "function")throw ("第一个参数必须是方法");var args = Array.from(arguments).splice(1);this.fnSources.push({fn: fn,args: args})};this.addWithContext = function (context,fn) {if (typeof fn !== "function")throw ("第二个参数必须是方法");var args = Array.from(arguments).splice(2);this.fnSources.push({fn: fn,args: args,context:context})};this.clear = function () {this.fnSources = [];this.excuting = false;}this.next = function () {if (this.excuting){return;}var fnObj = this.fnSources.splice(0, 1)[0];if (fnObj) {// console.log('next:'+this.excuting)this.excuting = true;fnObj.args.unshift(this);fnObj.fn.apply(fnObj.context, fnObj.args);}}this.finished = function () {// console.log('finished')this.excuting = false;}var that = this;setInterval(function () {that.next();}, 1000 / 60)}module.exports = mQueue
- 用class方法
class AsyncSerial{constructor() {this.cbList = [];}tap(fn) {this.cbList.push(fn);}call(end){let index = 0;let next = () => {if(index === this.cbList.length){end();return;}let fn = this.cbList[index];fn(() => {index++;next();})}next();}}let ap = new AsyncSerial();ap.tap((cb) => {setTimeout(() => {console.log(1);cb();}, 3000)})ap.tap((cb) => {setTimeout(() => {console.log(3);cb();}, 2000)});ap.call(() => {console.log('end');})
异步并行
class AsyncParallel {constructor() {this.cbList = [];}tap(fn) {this.cbList.push(fn);}call(end) {let index = 0;this.cbList.forEach(fn => {fn(() => {index++;if (index === this.cbList.length) { end() };});})}}let ap = new AsyncParallel();ap.tap((cb) => {setTimeout(() => {console.log(1);cb();}, 3000)})ap.tap((cb) => {setTimeout(() => {console.log(3);cb();}, 1000)});ap.call(() => {console.log('end');})
