【轉】關於js的 鏈式調用和流程控制 (sleep)


關於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")
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM