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

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

原文:https://blog.csdn.net/qq_37653449/article/details/83933724 html

實現下面的函數:           異步

new Test("test").firstSleep(3).sleep(5).eat("dinner")
//等待3秒
//test
//等待5秒
//dinner函數

鏈式調用沒什麼可說的 return this 就行了 ,此處的sleep 乍一看確實會引起一些思考,關鍵是異步以後個人this 在哪裏  ;那這個時候我就能夠建立一個異步隊列   ;整個實現能夠分爲三個核心部分 this

1,串接全部this (經過return this的方式)spa

2,把全部任務放到任務隊列裏面 .net

3,經過一個 方法有序執行隊列裏面的任務prototype

具體實現以下:code

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")
相關文章
相關標籤/搜索