发布订阅事件+异步函数说明
1. 监听触发事件:
class EventEmeitter {
constructor(){
this._events = this._events || new Map();
this._maxLength = this._maxLength || 10;
}
}
EventEmeitter.prototype.$on = function(type,fn){
const handle = this._events.get(type);
if(handle){
handle.push(fn);
}else{
this._events.set(type,[fn])
}
}
EventEmeitter.prototype.$emit = function(type,...args){
const handle = this._events.get(type);
for(let i=0;i<handle.length;i++){
handle[i].apply(this,args);
}
}
const emitter = new EventEmeitter()
emitter.$on('arson', man => {
console.log(`expel ${man}`);
});
emitter.$on('arson', man => {
console.log(`save ${man}`);
});
emitter.$on('arson', man => {
console.log(`kill ${man}`);
});
// 触发事件
emitter.$emit('arson', 'low-end');
2. 异步函数
async函数就是Generator函数的语法糖
async/await其实是基于Promise的
也就是 async/await是基于promise,用generator的语法糖实现的:
var promise = (prama)=>{
return new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve(prama);
},2000)
})
}
var genPromise = function *(){
yield promise('入参')
}
var gen = genPromise();
gen.next().value.then((val)=>{
console.log(val);
})
var asyncFun = async function(){
var one = await promise('rucan2');
return one;
}
asyncFun().then((val)=>{
console.log(val);
})
async/await 就是
getConstant() {
return 1
}
async getAsyncConstant() {
return 1
}
async getPromise() {
return new Promise((resolved, rejected)=> {
resolved(1)
});
}
async test() {
let a = 2
let c = 1
await getConstant();
let d = 3
await getPromise();
let d = 4
await getAsyncConstant();
return 2
}
使用了 promise进行了包裹
function getConstant() {
return 1;
}
function getAsyncConstant() {
return Promise.resolve().then(function () {
return 1;
});
}
function getPromise() {
return Promise.resolve().then(function () {
return new Promise((resolved, rejected) => {
resolved(1);
});
});
}
test() {
return Promise.resolve().then(function () {
let a = 2;
let c = 1;
return getConstant();
}).then(function () {
let d = 3;
return getPromise();
}).then(function () {
let d = 4;
return getAsyncConstant();
}).then(function () {
return 2;
});
}