async/await使用方法

async搭配await是ES7提出的,它的实现是基于Promise。经过同步方式的写法,使得代码更容易阅读。await函数不能单独使用,并且async函数返回的是一个Promise对象,可使用then函数添加回调函数。vue

示例1:web

async function testSync() {
   const response = await new Promise(resolve => {
       setTimeout(() => {
           resolve("async await test...");
         }, 1000);
    });
      console.log(response);
 }
 
testSync();//async await test...

示例2:
vue中的用法api

async getScheduleList(selectDate) {
	let response;
	// 这里request为向服务的发请求的方法
	await request(api.getScheduleList, {
		date: selectDate
	}).then(res => {
		response = res;
	});
	return response
}

init() {
	this.getScheduleList(selectDate).then(res => {
		console.log(res)
	})
}

示例3:async

swichMenu: async function() {
	//点击其中一个 menu
	const num = await  getNum()
	return num
}

swichMenu().then(res => {
	console.log(res)
})