关于js异步队列,搞懂这一篇就够了!

26 篇文章 1 订阅

前言、今天逛社区,无意间看到一道面试题,觉得很有意思,特此记录一下,题目如下

function LazyMan() {} //设计LazyMan函数满足下列需求
LazyMan('Tony');
// Hi I am Tony

LazyMan('Tony').sleep(10).eat('lunch');
// Hi I am Tony
// 等待了10秒...
// I am eating lunch

LazyMan('Tony').eat('lunch').sleep(10).eat('dinner');
// Hi I am Tony
// I am eating lunch
// 等待了10秒...
// I am eating diner

LazyMan('Tony').eat('lunch').eat('dinner').sleepFirst(5).sleep(10).eat('junk food');
// Hi I am Tony
// 等待了5秒...
// I am eating lunch
// I am eating dinner
// 等待了10秒...
// I am eating junk food

个人觉得这个题目还是很有意思的,结合了Promise,async/await,和js事件循环,异步队列的知识。

捣鼓了半个小时,中间一直修改优化,最终实现了一个版本,有兴趣的可以参考一下:

function LazyMan(name) {
	if(!(this instanceof LazyMan)) return new LazyMan(name)
	this.name = name 
	this.isExecute = false //队列是否开始执行
	this.cache = [] //缓存队列
	this.init()  //初始化需要做的事
}
LazyMan.prototype = {
	init: function () {
		console.log(`I am ${this.name}`)
	},
	eat: function(type) {
		this.cache.push(async () => {
			console.log(`${this.name} have ${type}`)
		})
		this.notify()
		return this;
	},
	sleep: function (t=0) {
		this.cache.push(async () => {
			return new Promise(res => {
				setTimeout(() => {
					res()
				},t)
			})
		})
		this.notify()
		return this
	},
	firstSleep: function  (t) {
		this.cache.unshift(async () => {
			return new Promise(res => {
				setTimeout(() => {
					res()
				},t)
			})
		})
		this.notify()
		return this
	},
	notify: function() {
		if(!this.isExecute) {
			this.isExecute = true
			setTimeout(() => {
				this.execute()
			},0)
		}
		return this
	},
	execute: async function (i) {
		i = i || 0
		if(i > this.cache.length-1) {
			this.isExecute = false
            this.cache = []
			return;
		}
		await this.cache[i]()
		this.execute(i+1)
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值