JavaScript同步和异步面试题
Posted 江州益彤
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaScript同步和异步面试题相关的知识,希望对你有一定的参考价值。
宏任务和微任务
js是单线程
宏任务
分类:setTimeout,setInterval,requrestAnimationFrame
微任务
分类:new Promise().then(回调),process.nextTick
一、
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() {
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();
以上是关于JavaScript同步和异步面试题的主要内容,如果未能解决你的问题,请参考以下文章