概念介绍
-
事件循环是js引擎管理js执行的一种机制,它把任务分为同步任务和异步任务,同步任务按顺序压到执行栈中执行,执行中产生的任务放到任务队列,等待同步代码执行完执行,任务队列又分为宏任务队列和微任务队列,同步代码执行完,优先看微任务队列,有则执行,微任务队列清空后看宏任务队列,任务执行中出现的新的异步任务同样放到队列,等待执行。我平常把整体代码看做一个宏任务,执行中遇到异步任务就放到队列,执行完宏任务执行跟着的微任务,清空微任务后算一个循环,微任务产生的微任务也在这一轮循环清空,因为微任务优先级高。
-
js引擎解析过程简单了解 js代码经过解析器解析成ast语法树,再通过解释器解释称字节码,字节码可直接执行,也可再编译成机器代码执行。 热点函数:字节码执行中,经过优化器,会提出一些经常使用的函数作为热点函数,再调用时直接调用机器代码,提升性能。如果参数类型突然变了,机器代码接收到参数不认识,就会反编译成字节码,再执行
-
自执行函数和await同行的代码都看作同步代码
-
throw new Error下面的代码是不执行的,进了catch也会进then
-
事件循环,按顺序。await同行代码是同步,后边是微任务
-
resolve后,throw new error无法捕获
-
new promise赋值语句中同步代码打印这个变量是undefined,得赋值完才能取到
-
catch要是执行,他后边的then就是他的,不执行,他后边的then就是上一个promise的
-
如果用await,他后边的代码放到微任务的时机需要时同行代码执行完,也就是最后再添加个then
做一做
console.log('aaa');
(async ()=>{
console.log('bbb');
await console.log('ccc');
console.log('eee')
})().then(()=>{
console.log('fff')
});
console.log('ddd');
console.log('aaa');
setTimeout(()=>console.log('t1'), 0);
(async ()=>{
console.log(111);
await console.log(222);
console.log(333);
setTimeout(()=>console.log('t2'), 0);
})().then(()=>{
console.log(444);
});
console.log('bbb');
setTimeout(() => {
console.log('0');
}, 0)
new Promise((resolve, reject) => {
console.log('1');
resolve();
}).then(() => { // w1
console.log('2');
// return
new Promise((resolve, reject) => {
console.log('3');
resolve(); // w2
}).then(() => { // 📌
console.log('4');
}).then(() => { // w4
console.log('5');
})
}).then(() => {
console.log('6'); //w3 📌
})
new Promise((resolve, reject) => {
console.log('7');
resolve()
}).then(() => {
console.log('8');
})
new Promise((resolve, reject) => {
console.log('promise');
for (var i = 0; i < 10000; ++i) {
i === 9999 && resolve(i);
}
console.log('promise after for-loop');
}).then((v) => {
console.log('promise1 i:'+v);
}).then(() => {
console.log('promise2');
});
setTimeout(() => {
console.log('timeout2');
}, 0);
requestAnimationFrame(() => {
console.log('requestAnimationFrame');
});
Promise.resolve().then(() => {
console.log('promise2');
});
console.log('end');
new Promise((res, rej) => {
console.log(1);
throw new Error('abc'); //抛出错误,下面的代码不执行
res(2);
console.log(3);
}).catch((e) => {
console.log('catch');
}).then((t) => {
console.log(t);
});
new Promise((res, rej) => {
console.log(1);
res(2); //状态发生转变后,后续的错误也无法捕获
console.error(4)
throw new Error('abc');
console.log(3);
}).catch((e) => {
console.log('catch');
}).then((t) => {
console.log(t);
});
let a;
const b = new Promise((resolve, reject) => {
console.log('promise1');
resolve();
}).then(() => {
console.log('promise2');
}).then(() => {
console.log('promise3');
}).then(() => {
console.log('promise4');
});
a = new Promise(async (resolve, reject) => {
console.log(a);
await b;
console.log(a);
console.log('after1');
await a // 后面的代码属于新的微任务,所以,后面非同步代码 且a第一步构造函数内未经历resolve。故a有值状态为pending
resolve(true);
console.log('after2');
}).then(data => {console.info(data)})
console.log('end');