关于js的 链式调用和流程控制 (sleep)
原文:https://blog.csdn.net/qq_37653449/article/details/83933724
实现下面的函数:
new Test("test").firstSleep(3).sleep(5).eat("dinner")
//等待3秒
//test
//等待5秒
//dinner
链式调用没什么可说的 return this 就好了 ,此处的sleep 乍一看确实会引发一些思考,关键是异步之后我的this 在哪里 ;那这个时候我就可以创建一个异步队列 ;整个实现可以分为三个核心部分
1,串接所有this (通过return this的方式)
2,把所有任务放到任务队列里面
3,通过一个 方法有序执行队列里面的任务
具体实现如下:
function Test(name) {
this.task = [];
let fn = () => {
console.log(name);
this.next();
}
this.task.push(fn);
setTimeout(() => {
this.next();
}, 0)
return this;
}
Test.prototype.firstSleep = function (timer) {
console.time("firstSleep")
let that = this;
let fn = () => {
setTimeout(() => {
console.timeEnd("firstSleep");
that.next();
}, timer * 1000)
}
this.task.unshift(fn);
return this;
}
Test.prototype.sleep = function (timer) {
console.time("sleep")
let that = this;
let fn = () => {
setTimeout(() => {
console.timeEnd("sleep");
that.next();
}, timer * 1000)
}
this.task.push(fn);
return this;
}
Test.prototype.eat = function (dinner) {
let that = this;
let fn = () => {
console.log(dinner);
that.next();
}
this.task.push(fn);
return this;
}
Test.prototype.next = function (dinner) {
let fn = this.task.shift();
fn && fn()
}
new Test("test").firstSleep(3).sleep(5).eat("dinner")