JS 微任务与宏任务, promise执行顺序

1 promise执行顺序

  var p = new Promise(function (resolve, reject) {
	console.log("1");
	resolve("2");
  })
  
  p.then((value) => {
	console.log(value);
  });

  console.log(3);
结果:1 3 2

new promise之后,promise立即执行,then方法是promise的回调函数,是异步的.而Promise不是

2 微任务与宏任务

微任务 早于 宏任务 执行. 记忆方法: 原则是越快的越先执行, 使得更早的看到页面出现东西. 宏任务如onclick需要时间长
微任务: Promise async/await
宏任务: setTimeout setInterval DOM事件 AJAX请求

	setTimeout(() => {
		console.log(1);
	}, 0);
	
	Promise.resolve().then(() => console.log(2));
	
	new Promise((resolve) => {
		resolve(3);
		console.log(4);
	}).then((data) => console.log(data));
	
	console.log(5);
//4  5  2  3  1

关于setTimeout的时间参数,指在 ms后将代码加入宏任务队列
setTimeout(() => {
	console.log(1);
}, 1000);
setTimeout(() => {
	console.log(2);
}, 0);
//2  1
所以宏任务队列是:  console.log(2);console.log(1);
posted @ 2022-02-27 15:27  波吉国王  阅读(137)  评论(0编辑  收藏  举报