【转】关于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")
相关文章
相关标签/搜索