This website requires JavaScript.
BING
诸佛龙象,众生马牛
转载

基于async/await的任务并发控制

共 1,514 字,需阅读 4 分钟2021/09/24 下午841 次阅读

本文转载自掘金,原文章地址 https://juejin.cn/post/7011400717843824654

          
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
/** * 编写一个异步任务调度器 */ class Scheduler { list = []; //用来承载还未执行的异步 count = 0; //用来计数 constructor(num) { this.num = num; //允许同时运行的异步函数的最大个数 } async add(fn) { // 锁 if (this.count >= this.num) { await new Promise((resolve) => { this.list.push(resolve); }); } this.count++; console.log('fn before executed'); const result = await fn(); console.log('fn executed'); this.count--; console.log('%c this.list.length %s', 'color: #bfffc8', this.list.length); // 如果有任务完成 则后面排队接上 if (this.list.length > 0) { console.log('this.list.shift()();'); this.list.shift()(); } return result; } } const schedule = new Scheduler(3); //最多同一时间让它执行3个异步函数 const asyncFactory = (n, time) => { return () => { return new Promise((resolve) => { setTimeout(() => { resolve(n); }, time); }); }; }; schedule.add(asyncFactory(1, 2000)).then((n) => { console.log(`异步任务:${n}`); }); schedule.add(asyncFactory(2, 2000)).then((n) => { console.log(`异步任务:${n}`); }); schedule.add(asyncFactory(3, 2000)).then((n) => { console.log(`异步任务:${n}`); }); schedule.add(asyncFactory(4, 2000)).then((n) => { console.log(`异步任务:${n}`); }); schedule.add(asyncFactory(5, 2000)).then((n) => { console.log(`异步任务:${n}`); }); schedule.add(asyncFactory(6, 2000)).then((n) => { console.log(`异步任务:${n}`); });
本文于2021/09/24 下午发布在
自由转载 - 署名 - 非商业性使用https://blog.felzx.cn/article/9
0 / 0 条看法
访客身份
在下有一拙见,不知...
期待你的捷足先登