Comments (4)
可以把任务看成三类:sleepFirst(微任务)、sayname(constructor任务)、eat&sleep(宏任务)
整个过程就是: 先串行执行微任务,再执行constructor任务,最后串行执行宏任务
class LazyMan {
constructor(name) {
this.name = name;
this.microTaskList = []; // 微任务
this.macroTaskList = []; // 宏任务
// Promise.resolve()使得先注册回调 再执行constructor
Promise.resolve()
.then(() => this.runInOrder(this.microTaskList))
.then(() => this.sayHello())
.then(() => this.runInOrder(this.macroTaskList));
}
sleepFirst(time) {
this.taskListAdd({type: 'micro', funcType: 'sleepFirst', params: {time}});
return this;
}
sleep(time) {
this.taskListAdd({type: 'macro', funcType: 'sleep', params: {time}});
return this;
}
eat(food) {
this.taskListAdd({type: 'macro', funcType: 'eat', params: {food}});
return this;
}
sayHello() {
console.log(`Hi This is ${this.name}`);
}
runInOrder(promiseArr) {
return promiseArr.reduce(
(prevPromise, nextPromise) => prevPromise.then(() => nextPromise()),
Promise.resolve()
);
}
taskListAdd({type, funcType, params}) {
let func = () => {};
switch (funcType) {
case 'sleep':
case 'sleepFirst':
func = () => new Promise(resolve => {
setTimeout(() => {
console.log(`Wake up after ${params.time}`);
resolve();
}, params.time * 1000);
});
break;
case 'eat':
func = () => new Promise(resolve => {
console.log(`Eat ${params.food}~`);
resolve();
});
break;
default:
break;
}
this[`${type}TaskList`].push(func);
}
}
from blog.
这是我想到的版本,看到这个题目,我没有自己去写任务队列,而是使用了系统级别的宏任务和微任务
class LazyMan {
constructor(name) {
this.name = name;
setTimeout(() => {
console.log("Hi! This is " + name);
}, 0);
}
sleep(seconds) {
const delay = seconds * 1000;
const time = Date.now();
while (Date.now() - time < delay) {
// hu lu lu ~~
}
setTimeout(() => {
console.log("wake up after " + seconds);
}, 0);
return this;
}
eat(something) {
setTimeout(() => {
console.log("eat " + something);
}, 0);
return this;
}
sleepFirst(seconds) {
new Promise((resolve) => {
const delay = seconds * 1000;
const time = Date.now();
while (Date.now() - time < delay) {
// hu lu lu ~~
}
resolve();
}).then(() => {
console.log("wake up after " + seconds);
});
return this;
}
}
function lazyMan(name) {
return new LazyMan(name);
}
lazyMan("Hank").sleep(2).eat("dinner").sleepFirst(3);
from blog.
学习了
from blog.
function lazyMan (name) {
const tasks = []
const methods = {
say(name) {
tasks.push(() => console.log(`Hi! This is ${name}`))
return this
},
eat(food) {
tasks.push(() => console.log(`Eat ${food}`))
return this
},
sleepFirst(time) {
tasks.unshift(() => new Promise(resolve => setTimeout(resolve, time * 1000)))
return this
},
sleep(time) {
tasks.push(() => new Promise(resolve => setTimeout(resolve, time * 1000)))
return this;
}
}
setTimeout(function run() {
if(!tasks.length) return
Promise.resolve(tasks.shift()()).then(run)
}, 0)
methods.say(name)
return methods
}
// lazyMan('think2011').sleep(3).eat('supper')
// lazyMan('think2011').eat('dinner').eat('supper')
lazyMan('think2011').sleepFirst(3).eat('supper')
我来一个不使用 class 的
from blog.
Related Issues (20)
- 设计模式之「结构型模式」 HOT 1
- 设计模式之「行为型模式」 HOT 3
- 分析生产环境的 Promise 实现,完整理解 Promise 原理
- 跟着 Event loop 规范理解浏览器中的异步机制 HOT 20
- _deprecated
- 简要分析前端代码从 Babel 编译到打包的流程
- [译] 资源提示 —— 什么是 Preload,Prefetch 和 Preconnect? HOT 4
- [译] Prefetch & preconnect-dns 的优先级 HOT 3
- 从一个极简 Node 服务器的实现中能学到什么?
- 浅谈 HTTP 缓存实践 HOT 3
- 浅析 React v16.3 新生命周期函数 HOT 1
- create-react-app 原理及源码分析 HOT 2
- Webpack 中 path/publicPath/contentBase 的关系 HOT 1
- koa2 源码及流程分析 HOT 1
- Knowledge fragment
- Knowledge fragment
- Knowledge fragment
- 如何优雅地彻底解决 antd 全局样式问题 HOT 9
- 不准备继续翻译了么
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from blog.