axios | 青训营笔记

71 阅读2分钟

这是我参与「第五届青训营 」伴学笔记创作活动的第9天

Promise对象doSomething()是异步的,当他在某个时间点执行成功后,会去回调then后面的doSomethingElse();doSomethingElse()也是异步的,当他执行成功后,会去回调doThirdThing();以此类推,形成了一个Promise链。 在回调地狱示例中,有 3 次 failureCallback 的调用,而在 Promise 链中只有尾部的一次调用。通常,一遇到异常抛出,promise 链就会停下来,直接调用链式中的 catch 处理程序来继续当前执行。

doSomething()
.then(result => doSomethingElse(value))
.then(newResult => doThirdThing(newResult))
.then(finalResult => console.log(`Got the final result: ${finalResult}`))
.catch(failureCallback);

除了串行执行若干异步任务外,Promise还可以并行执行异步任务。它依赖于前置的多个Promise对象,只有当这些Promise对象全部执行成功后,才会去执行then后面的回调函数。例如下面的promise对象p1和p2,这两个任务是可以并行执行的,用Promise.all()实现

var p1 = new Promise(function (resolve, reject) {
    setTimeout(resolve, 500, 'P1');
});
var p2 = new Promise(function (resolve, reject) {
    setTimeout(resolve, 600, 'P2');
});
// 同时执行p1和p2,并在它们都完成后执行then:
Promise.all([p1, p2]).then(function (results) {
    console.log(results); // 获得一个Array: ['P1', 'P2']
});

axios基于promise用于浏览器和node.js的http客户端,具有如下特点:

  • 支持浏览器和node.js
  • 支持promise
  • 能拦截请求和响应
  • 能转换请求和响应数据
  • 能取消请求
  • 自动转换JSON数据
  • 浏览器端支持防止CSRF(跨站请求伪造)

axios是基于ajax的一次封装。在实际工程中,接口统一规范好后,各组件axios的请求部分基本一致,因此可以将该部分分离出来做二次封装。被调用时接受组件传入的url等参数。其中baseURL会自动加入到url参数之前

import axios from 'axios'
import {Modal} from 'antd'export default class Axios {
​
    static ajax(options){
        return new Promise((resolve,reject) => {
            axios({
                url: options.url,
                baseURL:' https://www.easy-mock.com/mock/5d2bb8f85fb7810a6be03487/baseEndManager',
                method: 'get',
                timeout: 5000,
            }).then((response) => {
                if(response.status === 200){
                    let res = response.data;
                    resolve(res);
                }else{
                    Modal.info({
                        title: "警告",
                        content: "请求失败"
                    })
                    reject(response.data);
                }
            })
        })
    }
}

到Axios基于ajax和promise的特点,决定了axios是一个异步的过程。