1. <script>
  2. var baseUrl = "https://music.aityp.com/";
  3. $.ajax({
  4. url:baseUrl+"top/playlist",
  5. type:"get",
  6. data:{
  7. cat:"华语"
  8. },
  9. dataType:"json",
  10. success:res=>{
  11. var {playlists}= res;
  12. var item = playlists[0];
  13. console.log(item)
  14. $.ajax({
  15. url:`${baseUrl}playlist/detail?id=${item.id}`,
  16. type:"get",
  17. success:res=>{
  18. console.log(res)
  19. let id = res.playlist.trackIds[0].id;
  20. $.ajax({
  21. url:`${baseUrl}song/url?id=${id}`,
  22. success:res=>{
  23. console.log(res)
  24. }
  25. })
  26. }
  27. })
  28. }
  29. })
  30. </script>

二、promise

  • new Function

    1. new Array new 实例化的对象<br /> **我们使用promise的时候会将函数的状态暂停/凝固**<br /> new promise<br /> 1.使用New 关键字实现promise<br /> 2.promise 有两种状态resolve,reject<br /> 3.promise 函数不会马上触发,要通过一个then函数去触发<br /> 4.then触发的是resolve的状态,catch触发失败的状态<br /> resolve -->成功<br /> reject -->失败
<script>
        function go(){
            return new Promise((resolve,reject)=>{
                resolve(1);
                reject(2)
            })
        }
        go().then(res=>{
            console.log(1)
        }).catch(err=>{
            console.log(err)
        })
    </script>

三、封装promise

<script>
        function http(){
            return new Promise((resolve,reject)=>{
                $.ajax({
                    url:"https://music.aityp.com/top/playlist?cat=华语",
                    type:"get",
                    success:res=>{
                        resolve(res)
                    },
                    error:err=>{
                        reject(err)
                    }
                })
            })
        }
        http().then(res=>{
            console.log(res.playists)
        })
    </script>

四、p

<script>
        var p = new Promise((resolve,reject)=>{
            resolve("success");
            reject("失败")
        })
        p.then(res=>{
            console.log(res)
        })
        console.log("4")
    </script>

五、-promise

使用promise之后将http请求由纵向变为横向的了

<script>
        http("top/playlist?cat=华语").then(res=>{
            let id = res.playlists[0].id;
            return id
        }).then(res=>{
            http(`playlist/detail?id=${res}`).then(res=>{
                let id = res.playlist.trackIds[0].id;
                return id
            }).then(res=>{
                http(`song/url?id=${res}`).then(res=>{
                    console.log(res)
                })
            })
        })
    </script>

六、Ajax-p

 <script>
        var url = "https://music.aityp.com/top/playlist?tag=华语"  
        /* ajax就是一个promise */
        var ajax= $.ajax({url,type:"get"})  
        console.log(ajax)
        ajax.then(res=>{
            console.log(res)
        })
    </script>