js async await 使用方法
最编程
2024-04-21 06:59:00
...
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);
})
})
}