栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

您可以不使用Deferred来编写此代码吗?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

您可以不使用Deferred来编写此代码吗?

也许下面的内容只是穷人的递延方法,并没有真正解决问题的症结,但是除了递延队列之外,您还可以保留解析器功能队列。

这样可以在您的方法上节省少量代码,并避免显式使用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);


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/409756.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号