1、promise
promise用于解决回调地域问题,then是微任务,settimeout、setinterval是宏任务。
对于任务的执行顺序如下,开始阶段所有任务加入到主线程中,若遇到同步任务则直接执行,遇到微任务放到本任务队列的尾部,遇到宏任务则会开辟一个新的任务队列放在顶端,每个宏任务都会开辟一个新的任务队列,任务队列是有先后顺序的(顺序为开辟任务队列的顺序)。只有当前任务队列执行完成以后,才会执行下个任务队列。
练习题
console.log(1);
document.addEventListener("14", function () {
console.log(14);
});
new Promise(function (resolve) {
resolve();
console.log(2);
setTimeout(function () {
console.log(3);
}, 0);
Promise.resolve().then(function () {
console.log(4);
setTimeout(function () {
console.log(5);
}, 0);
setTimeout(function () {
(async function () {
console.log(6);
return function () {
console.log(7);
};
})().then(function (fn) {
console.log(8);
fn();
});
}, 0);
});
new Promise(function (resolve) {
console.log(9);
resolve();
}).then(function () {
new Promise(function (resolve, reject) {
console.log(10);
reject();
})
.then(function () {
setTimeout(function () {
console.log(11);
}, 0);
console.log(12);
})
.catch(function () {
console.log(13);
var evt = new Event("14");
document.dispatchEvent(evt);
});
});
});
setTimeout(function () {
console.log(15);
Promise.resolve().then(function () {
console.log(16);
});
}, 0);
2、async await
async await用于多个基本动作的异步实现
而promise用于一个基本动作的实现
async返回的是一个promise对象
async function fn(){
return 10;
}
var s = fn();
s.then(function(a){
console.log(10); //promise对象
})
//===============================================
function fns() {
return new Promise(function (resolve, rejct) {
var img = new Image();
img.src = "./img/1.png";
img.onload = function () {
resolve(img);//这个方法不行,img中没有数据
};
});
}
async function loadImage(){
var a=1;
var img=await fns();
var arr=[a,img];
return arr;
}
async function fn(){
var arr=await loadImage();
console.log(arr);
}
fn();
3、ts封装dispatchEvent
//event类文件EmitterEvent.ts
import EmitterTarget from "./EmitterTarget";
export default class EmitterEvent{
public target:EmitterTarget|null=null;
public currentTarget:EmitterTarget|null=null;
public type:string;
[key:string]:number|string|boolean|object|null;
constructor(type:string){
this.type=type;
}
}
//封装文件EmitterTarget.ts
import EmitterEvent from "./EmitterEvent";
interface IEventDic{
[key:string]:Array<Function|null>;
}
export default class EmitterTarget{
private eventDic:IEventDic={};
constructor(){
}
public addEventListener(type:string,listener:Function):void
{
if(this.eventDic[type] && this.eventDic[type].indexOf(listener)>-1) return;
if(!this.eventDic[type])this.eventDic[type]=[];
this.eventDic[type].push(listener);
}
public removeEventListener(type:string,listener:Function):void
{
var index=this.eventDic[type].indexOf(listener);
if(!this.eventDic[type] || index===-1) return;
this.eventDic[type][index]=null;
this.eventDic[type].splice(index,1);
}
public dispatchEvent(evt:EmitterEvent):void
{
if(!this.eventDic[evt.type] || this.eventDic[evt.type].length===0) return;
evt.currentTarget=this;
evt.target=this;
for(var i=0;i<this.eventDic[evt.type].length;i++){
(this.eventDic[evt.type][i] as Function).call(this,evt);
}
}
}