likes
comments
collection
share

使用async和await封装axios

作者站长头像
站长
· 阅读数 840

在最近的vue开发中ajax库选择了axios,需要根据回调函数的参数执行一个很长的代码块,执行函数加上axios参数代码量非常大不便于后期的优化和代码维护,于是我上网寻求axios异步的放法,被告知axios是promise返回值没有同步,如果代码量大可以尝试自行封装,于是研究了async和await

ES6Promise:

new Promise(function (resolve, reject) {
    console.log(1111);
    resolve(2222);
}).then(function (value) {
    console.log(value);
    return 3333;
})

生成一个异步函数如果执行成功就执行then中的函数如果失败就执行catch中的函数

async就是将一个普通函数返回为promise,当然在学习async和await时你需要先了解promise的用法

async function test() {
    return 'a'
}
test().then(res => {
    console.log(res);//"a"
})

test函数加上async会被转化为promise其中的return返回值就是then函数的参数

await只能使用在promise中(包括async的返回函数)其用途和他的中文含义差不多:等待,意思是必须等到加await的函数结束promise才会继续执行

import axios from 'axios';

async function createType(getData) {
 return  await axios({
        method: "POST",
        url: '/create-type',
        data: {
            type: getData.type
        }
    }).then(res => res.data)
    .catch(err=>{
       console.log(err);
       return []
    }); 
}
export default createType;
  1. 引入axios将

  2. createType转化为promise

  3. 设置变量data准备作为返回值

  4. 为axios函数添加await等待axios完全执行完createType才会返回data变量

  5. 请求成功后将axios的请求值赋值给变量data

  6. 将整个函数导出方便复用

项目导入函数

import createHtml from "@/modules/function/createHtml";
import updataHtml from "@/modules/function/updataHtml.js";
import updataArticle from "@/modules/article/updata-article";

ajax函数使用

createType({ type: type.value }).then((res) => {


});

!!:函数内对象为正常的函数传参

评论
请登录