«

同步和异步 Promise axios用法 async和await

yang 发布于 阅读:356 JS高阶阶段


1. 同步和异步

1.1 同步和异步的概念

同步:代码从上向下执行,一句一句运行,上一句未结束,下一句就等待
异步:代码从上向下执行,遇到异步代码放到任务队列中,同步代码执行结束,再根据条件执行异步

1.2 异步的场景

定时器
事件处理函数
ajax

1.3 回调函数

回调函数:回过头再调用的函数,现在不调用

异步一定有回调函数,回调函数不一定是异步

2. Promise对象

2.1 回调地狱

回调地狱就是回调函数中嵌套回调函数,维护起来特别麻烦,能解决异步的顺序问题

//请求第一个数据
ajax({
    method: 'get',
    url: './data.txt',
    success: function (d) {
        console.log(d);

        //请求第二个数据
        ajax({
            method: 'get',
            url: './data2.txt',
            success: function (d) {
                console.log(d);

                //请求第三个数据
                ajax({
                    method: 'get',
                    url: './data3.txt',
                    success: function (d) {
                        console.log(d);
                    }
                });
            }
        });
    }
});

2.2 什么是Promise?

Promise是ES6新增的承诺对象,用于将异步操作的结果传递出来

Promise有三种状态,两个结果:进行中 => 已成功 进行中 => 已失败

Promise对象有三个方法: .then() .catch() .finally()

2.3 Promise的基本用法

let p1 = new Promise(function (resolve, reject) {
    //异步代码
    setTimeout(function () {
        if (0) {
            resolve('请求成功!!!');
        } else {
            reject('请求失败???');
        }
    }, 1000);
});

//异步操作成功时,执行then方法
p1.then(function (res) {
    console.log('成功的方法:', res);
});

//异步操作失败时,执行catch方法
p1.catch(function (res) {
    console.log('失败的方法:', res);
});

//不管成功还是失败,都要执行
p1.finally(function () {
    console.log('不管成功还是失败,都要执行 finally ');
});

2.4 Promise其它方法

Promise.all() 将所有的Promise对象统一按顺序进行处理

Promise.resolve() 得到一个成功状态的Promise对象

Promise.reject() 得到一个失败状态的Promise对象

Promise.all([p1, p2, p3]).then(datas => {
    console.log(datas);
});

3. axios的用法

3.1 什么是axios?

Axios 是一个基于 promise 的网络请求库,可以用于浏览器和 node.js

3.2 axios的用法

//发get请求,传参数
axios.get('./data.txt', {
    params: {
        id: 11,
    }
}).then(res => {
    console.log(res)
});

//发post请求,传参数
axios.post('./data.txt', {
    username: '张三',
    age: 18,
}).then(res => {
    console.log(res)
});

//配置参数发请求-get请求
axios({
    method: 'get',
    url: './data2.txt',
    params: {
        id: 12,
    }
}).then(res => {
    console.log(res);
})

//配置参数发请求-post请求
axios({
    method: 'post',
    url: './data3.txt',
    data: {
        id: 12,
    }
}).then(res => {
    console.log(res);
})

4. async 和 await

async 异步,用于修饰函数,表示函数中有异步的代码

await 等待,出现在async修饰的函数中,用于等待异步操作的结果,等待Promise对象

//异步的终极解决方案:变同步,也就解决了回调地狱
async function show() {
    let p1 = await axios.get('./data.txt');
    console.log(p1);

    let p2 = await axios.get('./data2.txt');
    console.log(p2);

    let p3 = await axios.get('./data3.txt');
    console.log(p3);
}

同步和异步 Promise axios用法 async和await

版权所有:微4e
文章标题:同步和异步 Promise axios用法 async和await
除非注明,文章均为 微4e 原创,请勿用于任何商业用途,禁止转载

推荐阅读:


扫描二维码,在手机上阅读
请先 登录 再评论