JavaScript同步、异步和process.nextTick、setImmediate面试题

一、基础:同步程序执行完再执行异步程序

二、执行顺序

在这里插入图片描述
在这里插入图片描述

三、事件循环

在这里插入图片描述

四、宏任务和微任务(异步)

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();

在这里插入图片描述

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值