js基础知识——async 与 await
一、async 与 await
- async 与 await是Promise 的一种调用方案(也就是必须结合promise 一起使用),能够将异步代码写的像“同步代码一样”
- async :书写在一个函数的开头,表明当前函数是一个异步函数,内部可以书写await
- await :具有等待含义,书写在异步函数前,代码运行到这个位置时,会有一个等待效果,一直等到这个异步任务结束,并且将异步任务的反馈结果 当一个值返回出来
function fn () {
const p = new Promise(function (resolve,reject){
const timer = Math.ceil(Math.random() * 3000) //向上取整
console.log('班长买水')
setTimeout(() => {
if (timer > 2500){
reject('失败,因为超时')
}else {
resolve('成功,因为没超时')
}
},timer)
})
return p
}
newFn()
async function newFn(){
// 因为开头写了async,所以这个函数是一个独特的异步函数,内部可以书写await
// await 等待,必须等待后边的promise结束后再往下继续执行代码
const r1 = await fn()
console.log('第一次买水:',r1)
const r2 = await fn()
console.log('第二次买水:',r2)
const r3 = await fn()
console.log('第三次买水:',r3);
}
二、async 与 await 缺点及解决方法
- 缺点:不能正常捕获到promise 的失败状态
解决方法1: try... catch
//解决方案1.try... catch
function fn () {
const p = new Promise(function (resolve,reject){
const timer = Math.ceil(Math.random() * 3000) //向上取整
console.log('班长买水')
setTimeout(() => {
if (timer > 200){
reject('失败,因为超时')
} else {
resolve('成功,因为没超时')
}
},timer)
})
return p
}
newFn()
async function newFn(){
try{
const r1 = await fn()
console.log('第一次买水:',r1)
} catch (error) {
console.log(error)
}
}
解决方法2.封装一个永远不会失败的promise
- 也就是说不管请求状态如何,永远调用resolve让promise的状态一定是成功,为了区分这次请求是成功还是失败,我们不再单纯的返回一个字符串,而是返回一个 对象
- 注意:这个对象,我们约定里面有一个code 属性,成功时赋值为1,失败时赋值为0
// 解决方法2:封装一个永远不会失败的promise
function fn () {
const p = new Promise(function (resolve,reject){
const timer = Math.ceil(Math.random() * 3000) //向上取整
console.log('班长买水')
setTimeout(() => {
if (timer > 2500){
resolve({
code:0, //代表当前请求失败
msg:'超时,所以买水失败'
})
} else {
resolve({
code:1, //代表当前请求成功
msg:'未超时,所以买水成功'
})
}
},timer)
})
return p
}
newFn()
async function newFn(){
const r1 = await fn()
console.log(r1)
if (r1.code === 0) {
console.log('请求失败的补救措施')
} else {
console.log('请求成功,正常执行代码')
}
}