事件环,任务队列,js执行机制总结

  1. await 后面接的代码为同步代码 下一行代码为异步代码
		async function a() {
			await b;
			console.log(3);
		}

		function b() {
			console.log(2);
		}
		a();
		console.log(1);
		// 打印结果为 1,2 ,3
		// 改造成promise为
		function a() {
			new Promise((resolve, reject) => {
				function b() {
					console.log(2);
				}
				b();
			}).then((res) => {
				console.log(3);
			})
		}
		a();
		console.log(1);
  1. await 后面的函数中没有返回执行状态,则后面的代码不会执行
		const async1 = async () => {
			console.log('1'); // 2
			setTimeout(() => {
				console.log('2'); // 6
			})
			await new Promise(resolve => {
				console.log('3'); // 3
			})
			// 以下不执行, await后面的promise没有返回执行后的状态
			console.log('4'); 
			return '5';
		}
		console.log('6'); // 1
		async1().then(res => console.log(res)); // 不执行 async1没有返回执行后的状态
		console.log('7'); // 4
		Promise.resolve(1)
		.then(2)
		.then(Promise.resolve(3))
		.catch(4)
		.then(res => console.log(res)) // 5 1
  1. Promise执行完成后才会赋值执行状态
		a = new Promise(async (resolve) => {
			resolve(true);
			console.log(a); // undefined
			await b;
			console.log(a); // promise filled
			console.log(5); //

			await a;
			console.log(6); //
		})
  1. Promise的 reject()会中断后面的执行,catch捕获后能正常执行
		async function a(){
			await new Promise((resolve, reject) => {
				reject('222')
			})
			// reject状态会终断执行
			console.log('2');
			return Promise.resolve('4');
		}
		a().then((res) => {
			console.log(res)
		})
		console.log(5)
		// 改为正常执行
		sync function a(){
			await new Promise((resolve, reject) => {
				reject('222')
			}).catch((err) =>{
				console.log(err)
			});
			console.log('2');
			return Promise.resolve('4');
		}
		a().then((res) => {
			console.log(res)
		})
		console.log(5)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值