async & await

async & await

简介

async:异步,用于定义函数为异步函数,定义的异步函数返回一个promise

await:等待,等待promise执行resolve

ES2017之前处理异步一般都是promise,之后加入了async & await

async & await本身时建立在promise的基础上,所以要更好的理解async & await需要清楚promise工作方式

let a = async () => {
    
    
	return await new Promise((resolve) => {
    
    
		setTimeout(() => {
    
    
			resolve('hello ')
		}, 100)
	})
}

let b = async () => {
    
    
	return 'world'
}

let all = async () => {
    
    
	let resA = await a()
	let resB = await b()
	resA += resB
	return resA
}
all().then(console.log)
// 输出结果:
// hello world

为什么使用async & await

  • 突破的promise中.then().then()…的链条
  • 语法上看起来更像同步操作
  • 在开发过程中更方便调试异步代码,promise会跳过异步代码

猜你喜欢

转载自blog.csdn.net/BDawn/article/details/108512308