async
- async 的本质就是会隐式的返回一个 Promise 对象
const getInfo = async () => {
return 'hello world'
}
getInfo() // Promise {<fulfilled>: "hello world"}
- 声明为 async 的函数,默认的返回值就是一个 Promise 对象,等同于
const getInfo = async () => {
return Promise.resolve('hello world')
}
getInfo() // Promise {<fulfilled>: "hello world"}
- async声明function是一个异步函数,返回一个promise对象,可以使用 then 方法添加回调函数
- async函数内部return语句返回的值,会成为then方法回调函数的参数
const getInfo = async () => {
return Promise.resolve('hello world')
}
getInfo().then(res => {
console.log(res) // hello world
})
- async函数返回的 Promise 对象被reject,可以在catch中捕获
const getInfo = async () => {
return Promise.reject('出错了')
}
getInfo().then(res => {
console.log(res)
}).catch(err => {
console.log(err) // 出错了
})
await
- await 操作符只能在异步函数 async function 内部使用
- 如果一个 Promise 被传递给一个 await 操作符,await 将等待 Promise 正常处理完成并返回其处理结果,也就是说它会阻塞后面的代码,等待 Promise 对象结果
- 如果等待的不是 Promise 对象,则返回该值本身
const getMsg1 = () => {
return Promise.resolve('test1')
}
const getMsg2 = () => {
return Promise.resolve('test2')
}
const resultMsg = async () => {
const [p1, p2] = await Promise.all([getMsg1(), getMsg2()])
console.log(p1, p2)
}
resultMsg()
console.log('我先执行')
执行结果:'我先执行' -> 'test1 test2'
错误处理
- 如果await后面的异步操作出错,那么等同于async函数返回的 Promise 对象被reject
- 防止出错的方法,也是将其放在try...catch代码块之中
const getMsg1 = () => {
return Promise.resolve('test1')
}
const getMsg2 = () => {
return Promise.reject('出错了')
}
const resultMsg = async () => {
try {
const [p1, p2] = await Promise.all([getMsg1(), getMsg2()])
if (p1 && p2) {
console.log(p1, p2)
}
} catch (e) {
console.log(e)
}
}
resultMsg()
模拟接口
// 模拟接口
function request() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const res = {
code: 200,
data: [{
name: 'zhang',
age: 10
}]
}
if (res && res.code === 200) {
resolve(res)
} else {
reject('请求失败')
}
}, 3000)
})
}
// 请求接口
const getInfo = async () => {
try {
let res = await request()
if (res && res.code === 200) {
console.log(res.data)
}
} catch (err) {
console.log(err)
}
}
getInfo()
网友评论