也许下面的内容只是穷人的递延方法,并没有真正解决问题的症结,但是除了递延队列之外,您还可以保留解析器功能队列。
这样可以在您的方法上节省少量代码,并避免显式使用Deferreds。
我不知道是否存在已建立的模式,但是它本身似乎是用于维护异步对象池的可重用模式,因此
WorkerList可以调用它而不是调用它,而是将其命名
AsyncPool为可重用的部分在您的
WorkerList:
class AsyncPool { constructor() { this.entries = []; this.resolverQueue = []; } add(entry) { console.log(`adding ${entry}`); this.entries.push(entry); // if someone is waiting for an entry, // pull the oldest one out of the list and // give it to the oldest resolver that is waiting while (this.resolverQueue.length && this.entries .length) { let r = this.resolverQueue.shift(); r(this.entries.shift()); } } // if there's an entry, get one immediately // if not, return a promise that resolves with an entry // when next one is available get() { return new Promise((r) => this.entries.length ? r(this.entries.shift()) : this.resolverQueue.push(r) ); }}let pool = new AsyncPool();pool.add('Doc');pool.add('Grumpy');pool.get().then(console.log);pool.get().then(console.log);pool.get().then(console.log);pool.get().then(console.log);// add more entries latersetTimeout(() => pool.add('Sneezy'), 1000);setTimeout(() => pool.add('Sleepy'), 2000);
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)