jquery:promise解决回调地狱

185 阅读1分钟
<script>
    // axios('..')
    // .then(res=>{
    //     /* 返回 地球 月球 */
    //     /* 。。。。 */
    // })
    // .then(res=>{
    //     /* 返回 美洲 亚洲 */
    // })
    // .then(res=>{
    //     /* 返回中国 美国 */
    // })

    /* console.log(Promise); */
    /**
     * 功能:用来解决回调地狱
     * @params Function
     * */
    new Promise(
        /**
         * @params resolve Function 请求已经完成的时候调用
         * @params reject Function 请求发送失败的时候调用
         * */
        function (resolve,reject){
            $.ajax({
                url:"xingqiu.txt",
                success:function(res){
                    /* 返回 地球 月球 */
                    resolve(res)
                },
                error:function(err){
                    reject(err)
                }
            })
        }
    )
    /* .then里面只有一个回调函数是用来接收请求成功后得到的数据 */
    // .then(data=>{
    //     console.log('then1:',data);
    //     /* 如果需要传给下一个then 需要return你要传的数据 */
    //     return '地球';
    // })
    // /* .catch是用来捕获失败的时候得到的错误信息的 */
    // .catch(error=>{
    //     console.log('catch1:',error);
    // })
    
    /* .then里面有两个回调函数,第一个表示请求成功,
    第二个表示请求失败的时候调用 */
    // .then(data=>{
    //     console.log('then1:',data);
    //     return '地球';
    // },error=>{
    //     console.log('catch1:',error);
    // })
    .then(data=>{
        console.log('then2:',data.substring(0,3) );
        return new Promise(resolve=>{
            $.ajax({
                url:'./zhou.txt?name='+data,
                success:function(res){
                    // console.log('第二个请求拿到的洲数据',res);
                    resolve('亚洲')
                },
                error:function(err){
                    // console.log(err);
                    // console.log('提示:接口请求失败');
                }
            })
        })
    })
    .then(data=>{
        console.log('then3:',data);
        return new Promise(resolve=>{
            $.ajax({
                url:'./guo.txt?name='+data,
                success:function(res){
                    console.log('第三个请求拿到最终的数据',res);
                },
                error:function(err){
                    // console.log(err);
                    // console.log('提示:接口请求失败');
                }
            })
        })
    })
    /* 把第二个请求的错误信息打印出来 */
    

</script>