From 049eb7a5319f46c33cee00a2fe2f35dd2c7e5d17 Mon Sep 17 00:00:00 2001 From: mogu Date: Fri, 31 Jul 2020 13:49:22 +0800 Subject: [PATCH] mainshi --- .../\345\244\264\346\235\241.js" | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 "\351\235\242\350\257\225\351\242\230/\345\244\264\346\235\241.js" diff --git "a/\351\235\242\350\257\225\351\242\230/\345\244\264\346\235\241.js" "b/\351\235\242\350\257\225\351\242\230/\345\244\264\346\235\241.js" new file mode 100644 index 0000000..23ed2e0 --- /dev/null +++ "b/\351\235\242\350\257\225\351\242\230/\345\244\264\346\235\241.js" @@ -0,0 +1,78 @@ +/* +class Manager { + constructor(max) { + this.max = max; + } + + add(fn) { // fn: () => Promise + + } + } + + + const wrapper = (str, time) => { + return () => { + return new Promise(res => { + setTimeout(() => { + console.log(str); + + res(); + }, time) + }) + + } + } + + const m = new Manager(2); + + m.add(wrapper('a', 1000)); + m.add(wrapper('b', 500)); + m.add(wrapper('c', 300)); + + 0 start + 500 b + 800 c + 1000 a + */ + + + class Manager { + constructor(max) { + this.max = max + this.cbs = [] + this.queen = [] + } + add(fn) { + if(this.cbs.length < this.max) { + this.cbs.push(fn) + fn().then(res => { + let index = this.cbs.indexOf(fn) + this.cbs.splice(index, 1) + if(this.queen.length > 0) { + this.add(this.queen.shift()) + } + }) + } else { + this.queen.push(fn) + } + } + } + + const wrapper = (str, time) => { + return () => { + return new Promise(res => { + setTimeout(() => { + console.log(str); + + res(); + }, time) + }) + + } + } + + const m = new Manager(2); + + m.add(wrapper('a', 1000)); + m.add(wrapper('b', 500)); + m.add(wrapper('c', 300)); \ No newline at end of file