任务调动

异步并行

几个异步同时执行,最后一个执行完毕调用一下回调方法

  • 原生JavaScript

当多个任务要串行执行,结果要统一处理时,将多个任务放入队列中执行,直到所有任务结束才结束,一分钟执行60次

  1. var mQueue = function () {
  2. this.fnSources = [];
  3. this.excuting = false;
  4. this.add = function (fn) {
  5. if (typeof fn !== "function")
  6. throw ("第一个参数必须是方法");
  7. var args = Array.from(arguments).splice(1);
  8. this.fnSources.push({
  9. fn: fn,
  10. args: args
  11. })
  12. };
  13. this.addWithContext = function (context,fn) {
  14. if (typeof fn !== "function")
  15. throw ("第二个参数必须是方法");
  16. var args = Array.from(arguments).splice(2);
  17. this.fnSources.push({
  18. fn: fn,
  19. args: args,
  20. context:context
  21. })
  22. };
  23. this.clear = function () {
  24. this.fnSources = [];
  25. this.excuting = false;
  26. }
  27. this.next = function () {
  28. if (this.excuting){
  29. return;
  30. }
  31. var fnObj = this.fnSources.splice(0, 1)[0];
  32. if (fnObj) {
  33. // console.log('next:'+this.excuting)
  34. this.excuting = true;
  35. fnObj.args.unshift(this);
  36. fnObj.fn.apply(fnObj.context, fnObj.args);
  37. }
  38. }
  39. this.finished = function () {
  40. // console.log('finished')
  41. this.excuting = false;
  42. }
  43. var that = this;
  44. setInterval(function () {
  45. that.next();
  46. }, 1000 / 60)
  47. }
  48. module.exports = mQueue
  • 用class方法
  1. class AsyncSerial{
  2. constructor() {
  3. this.cbList = [];
  4. }
  5. tap(fn) {
  6. this.cbList.push(fn);
  7. }
  8. call(end){
  9. let index = 0;
  10. let next = () => {
  11. if(index === this.cbList.length){
  12. end();
  13. return;
  14. }
  15. let fn = this.cbList[index];
  16. fn(() => {
  17. index++;
  18. next();
  19. })
  20. }
  21. next();
  22. }
  23. }
  24. let ap = new AsyncSerial();
  25. ap.tap((cb) => {
  26. setTimeout(() => {
  27. console.log(1);
  28. cb();
  29. }, 3000)
  30. })
  31. ap.tap((cb) => {
  32. setTimeout(() => {
  33. console.log(3);
  34. cb();
  35. }, 2000)
  36. });
  37. ap.call(() => {
  38. console.log('end');
  39. })

异步并行

  1. class AsyncParallel {
  2. constructor() {
  3. this.cbList = [];
  4. }
  5. tap(fn) {
  6. this.cbList.push(fn);
  7. }
  8. call(end) {
  9. let index = 0;
  10. this.cbList.forEach(fn => {
  11. fn(() => {
  12. index++;
  13. if (index === this.cbList.length) { end() };
  14. });
  15. })
  16. }
  17. }
  18. let ap = new AsyncParallel();
  19. ap.tap((cb) => {
  20. setTimeout(() => {
  21. console.log(1);
  22. cb();
  23. }, 3000)
  24. })
  25. ap.tap((cb) => {
  26. setTimeout(() => {
  27. console.log(3);
  28. cb();
  29. }, 1000)
  30. });
  31. ap.call(() => {
  32. console.log('end');
  33. })