一、基础:同步程序执行完再执行异步程序
二、执行顺序
三、事件循环
四、宏任务和微任务(异步)
js是单线程
4.1、宏任务(异步)
分类:
1、计时器:setTimeout,setInterval
2、Ajax
3、读取文件
4.2、微任务(异步)
分类:
1、process.nextTick也是微任务,这里顺序只是为了理解方便单独提出来了
2、Promise().then(回调),
4.3、Promise和async、await
4.3.1、Promise(微任务)
4.3.2、async、await (微任务)
面试题一、
async function async1() {
console.log('async1 start');
await async2();
console.log('async1 end');
}
async function async2() {
console.log('async2');
}
console.log('script start');
setTimeout(function() {
console.log('setTimeout');
},0)
async1();
new Promise(function(resolve) {
console.log('promisel');//这里面的代码时同步的
resolve();
}).then(function() {//then里面的代码才是异步的
console.log('promise2');
});
console.log('script end');
或(浏览器的原因,ie8以上的浏览器先输出then再执行其他)
面试题二、
async function async1() {
console.log('async1 start');
await async2();
console.log('async1 end');
}
async function async2() {
console.log('async2');
}
console.log('script start');
setTimeout(function() {
console.log( 'setTimeout');
}, 0)
async1();
console.log('script end');
script start
async1 start
async2
script end
async1 end
setTimeout
三、
function app() {
setTimeout(() => {
console.log("1-1");
Promise.resolve().then(() => {
console.log("2-1");
});
});
console.log("1-2");
Promise.resolve().then(() => {
console.log("1-3");
setTimeout(() => {
console.log("3-1");
});
});
}
app();