异步函数处理 Promise async/await

292 阅读2分钟
// http请求工具
import axios from 'axios'

// Promise处理异步
// 看了文档的小伙伴应该看到下面这些字眼
// 1、promise对象
// 2、then、catch
// 其实就是如果一个变量时promise对象,那他可以接上then、catch
// 例如
const res = new Promise((resolve, reject) => {
    const url = '/api/list'
    // 这个请求工具返回的就是promise对象
    axios.get(url).then(res => {
        resolve()
    }).catch(() => {
        reject()
    })
})
res.then(() => {
    console.log('success')
}).catch(() => {
    console.log('error')
 })

// async await处理异步 (就是promise的语法糖,简单理解就是简写版本,工作中用的多!)
// try catch 用来捕捉异常,【总得有一处捕需要捉异常】,否者代码会中断
// 不用觉得try catch 很丑,实际应用中很少会去特殊处理单一请求的异常,而通常是整个项目全局处理,以为接口
// 出了异常,一般操作就是弹窗提示,如果还需要别的操作,那就需要包上一层try catch啦
async function () {
    try {
        const url = '/api/list'
        const res = await axios.get(url)
        console.log('success')
    } catch {
        console.log('error')
    }
}

// 当下一个接口需要等待上一个接口请求结果,就会出现地狱回调
// 以下例子默认成功调用接口
// 地狱回调
axios.get(url1).then(res1 => {
    axios.get(url2).then(res2 => {
        axios.get(url3).then(res3 => {
            axios.get(url4).then(res4 => {
                axios.get(url5).then(res5 => {
                    // ...
                })
            })
        })
    })
})

// 利用Promise处理
const res1 = new Promise((resolve, reject) => {
    axios.get(url1).then(res => {
        resolve()
    })
})
// res1得到promise对象,上面代码默认是执行成功调用then(失败是调用catch)
const res2 = res1.then(() => {
    return new Promise((resolve, reject) => { // 别忘了return res2才能拿到promise对象 后面才会有res2.then
        axios.get(url2).then(res => {
            resolve()
        })
    })
})
const res3 = res2.then(() => {
    return new Promise((resolve, reject) => {
        axios.get(ur3).then(res => {
            resolve()
        })
    })
})
const res4 = res3.then(() => {
    return new Promise((resolve, reject) => {
        axios.get(ur4).then(res => {
            resolve()
        })
    })
})
...
// async await
async function () {
    const res1 = await axios.get(url1)
    const res2 = await axios.get(url2)
    const res3 = await axios.get(url3)
    const res4 = await axios.get(url4)
    ...
}
// 看到了区别了嘛?
// 上面用promise连续4次调用函数,如果再第2次出错了,res2.catch()没有写来捕捉异常,则代码不会往下走,所以平时不要忘记捕捉异常哦

// 看到这里还不清楚的小伙伴可以把每一步的结果console出来看看,看了就明白了了
// 记住 then catch 是接在 promise对象的