关于Promise

84 阅读1分钟
<!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>
    <!-- 导入jQuery -->
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>

<body>

</body>
<script>
    /* 
    目的:将Ajax封装成一个promise 对象,获取数据想使用.then()===$.ajax().then() */
    $(function () {
        // 一、发送请求
        // $.ajax({
        //     url:'http://www.liulongbin.top:3005/api/getlunbo',
        //     data:{},
        //     success:function(res){
        //         console.log(res);
        //     }
        // })

        // 二、promise改造
        function ajaxPromise() {
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: 'http://www.liulongbin.top:3005/api/getlunbo',
                    data: {},
                    success: resolve
                })
            })
        }
        // console.log(ajaxPromise());

        // ajaxPromise().then(res=>{
        //     console.log(res);
        // })

        const hello=async()=>{
            const res = await ajaxPromise()
            console.log(res);
        }
        hello()
    })
</script>

</html>