9.使用async和await简化promise的使用

我们常规的写法如下:
reqLogin(username, password).then(response => {
    console.log("登陆成功了!", response.data)
}).catch(error => {
    console.log("登陆失败了!", error)
})

而我们使用async和await代替后的写法如下:

// async 与 await 简化 promise的使用,即取代了 .then .catch, 实际就是为了同步 如下:
try {
    const response = await reqLogin(username, password)
    console.log("请求成功了!", response.data)
} catch (e) {
    console.log("请求失败了!", e)
}

async和await的作用:
 
1.作用?
    简化promise对象的使用:不再使用then() /catch() 来指定成功/失败的回调函数;
    以同步编码(没有回调函数)方式实现异步流程;
2.哪里写await?
    在返回promise的表达式左侧写await:不想要promise,想要promise异步执行成功后的response数据;
3.哪里写async?
    await所在函数(最近的)定义的左侧async; 
最终版本在api/ajax.js文件内容如下:
import axios from 'axios'
import {message} from 'antd'
export default function ajax(url, data={}, method='GET') {
    // 执行器函数 executor
    // Promise 新建时,传入执行器函数 executor
    return new Promise((resolve, reject) => {
        let promise
        // 1.执行异步ajax请求
        if(method === 'GET') {
            // 发送get请求: url  参数配置对象
            promise = axios.get(url, { params: data},)
        }else{
            // 发送post请求
            promise = axios.post(url, data)
        }
        // 2.如果执行成功了,调用resolve
        promise.then(response => {
            resolve(response.data)
        }).catch(error => {
            // 3.如果失败了,不调用reject【调用的话会触发try catch, 而我们不想写try catch】,而是提前抛出异常信息
            message.error("请求出错了:" + error.message)
        })
    })
}

 

posted @ 2023-03-10 17:48  以赛亚  阅读(62)  评论(0编辑  收藏  举报