js async await 用法

async/await 是 JavaScript 中用于处理异步操作的一种语法糖,它使得异步代码看起来像同步代码一样直观和易读。它是用同步的语法写异步的代码。
1. 基础概念
一,async:关键字用于声明一个函数是异步的。一个标记为 async 的函数总是返回一个 Promise 对象。
二,await:关键字仅能在 async 函数内部使用,用于等待一个 Promise 完成并返回其结果。它会暂停当前的 async 函数的执行,直到 Promise 完成,然后继续执行 async 函数,并返回解析后的 Promise 值。
2.async和await与Promise的关系
1,执行async函数,返回的是一个promise对象
2,await相当于promise的then
3,try…catch可捕获异常,代替了Promise的catch

调用一个函数

function timeout(){
	 return new Promise((resolve,reject)=>{
		 setTimeout(e=>{
			 console.log('hi');
			 resolve('success')
		 },3000)
	 })
}
async function f(){
	const data = await timeout();
	console.log(data);
	console.log('result');
}
f()
//执行顺序 hi success result

使用try…catch捕获异常

(async function fn(){
	let res = Promise.reject('error')
	try{
		const result = await res
		console.log(result);
	}catch(e){
		console.log(e);
	}
})()
//error

async await 用于数组循环

async getarr(){
	// 循环多个条件
	let arr = [2,3,4,5]
	for (let s of arr) {
		console.log(s);
		this.SetUpType = s
		await this.gethouse()
	}
}
gethouse(){
	let data = {
		houseType:this.houseType,
		SetUpType:this.SetUpType
	}
	return new Promise((resolve,reject)=>{
		this.$http.get('/houseSetUp/query', data).then(res => {
			console.log(res,'res' + this.SetUpType);
			 resolve(); 
		}).catch(err=>{
			console.log(err);
		})
	})
}
  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值