javascript实现异步编程的方法

一、异步编程的方法
1、回调函数
2、事件监听
3、发布/订阅
4、Promise对象
5、Generator函数
6、async函数
二、例子

1、回调函数

setTimeout(()=>{
    console.log(111);
    setTimeout(()=>{
        console.log(222);
        setTimeout(()=>{
            console.log(333);
        },3000)
    },2000)
},1000)

2、Generator函数

function one() {
    setTimeout(() => {
        console.log(111);
        i.next();
    }, 1000);
};
function two() {
    setTimeout(() => {
        console.log(222);
        i.next();
    }, 2000);
};
function three() {
    setTimeout(() => {
        console.log(333);
    }, 3000);
};
function* gen() {
    yield one();
    yield two();
    yield three();
}
let i = gen();
i.next()

3、asyn函数

function one() {
    setTimeout(() => {
        console.log(111);
    }, 1000);
};
function two() {
    setTimeout(() => {
        console.log(222);
    }, 3000);
};
function three() {
    setTimeout(() => {
        console.log(333);
    }, 6000);
};
async function gen() {
    await one();
    await two();
    await three();
}
gen()

4、Promise对象

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 基于promise封装ajax
        let axios = {
            get(url) {
                return new Promise(function (resolve, reject) {
                    // ajax网络请求
                    // 1.创建XHR实例
                    let xhr = new XMLHttpRequest();
                    // 2.设置请求行
                    xhr.open('get', url,);
                    // 3.设置请求头
                    xhr.setRequestHeader('Content-Type', 'application/json');
                    // xhr.responseType = 'json';
                    // 4.发送请求
                    xhr.send();//接受一个参数,这个参数会放到请求体中
                    // 5.监听
                    xhr.onreadystatechange = function () {
                        console.log(this);
                        if (this.readyState == 4) {
                            if(this.status == 200){
                                resolve(this.response)
                            }else {
                                reject(this.response)
                            }
                        }
                    }
                })
            }
        }
        let baseUrl = 'http://47.100.226.238:8888'
        axios.get(baseUrl+'/index/category/findAll').then((res)=>{
            console.log(res);
        }).catch((res)=>{
            console.log(res);
        })
        </script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值