1.promise 将函数的状态暂停/凝固

解决回调地狱

  1. <script>
  2. /* 我们使用promise的时候会将函数的状态暂停/凝固
  3. new Promise
  4. 1.使用new 关键字实现promise
  5. 2.promise有两种状态resolve,reject
  6. 3.promise函数不会马上触发,要通过一个then函数去触发
  7. 4.then触发的是resolve(成功)的状态,catch触发失败的状态
  8. resolve -->成功
  9. reject -->失败
  10. */
  11. function go(){
  12. return new Promise((resolve,reject)=>{
  13. resolve(1);
  14. reject(2)
  15. })
  16. }
  17. // go().then(res=>{
  18. // console.log(res)
  19. // }).catch(err=>{
  20. // console.log(err)
  21. // })
  22. </script>

2.封装promise

  1. <script>
  2. function http(){
  3. return new Promise((resolve,reject)=>{
  4. $.ajax({
  5. url:"https://music.aityp.com/top/playlist/cat=华语",
  6. type:"get",
  7. success:res=>{
  8. resolve(res)
  9. },
  10. error:err=>{
  11. reject(err)
  12. }
  13. })
  14. })
  15. }
  16. http().then(res=>{
  17. console.log(res)
  18. })
  19. </script>

3.网易云

  1. //http-promise.js
  2. var baseUrl="https://music.aityp.com/"
  3. function http(url){
  4. return new Promise((resolve,reject)=>{
  5. $.ajax({
  6. url:baseUrl+url,
  7. type:"get",
  8. dataType:"json",
  9. success:res=>{
  10. resolve(res)
  11. },
  12. error:err=>{
  13. reject(err)
  14. }
  15. })
  16. })
  17. }
  1. //promise.html
  2. <script>
  3. http("top/playlist?cat=华语").then(res=>{
  4. let id=res.playlists[0].id;
  5. return id
  6. }).then(res=>{
  7. http(`playlist/detail?id=${res}`).then(res=>{
  8. let id=res.playlist.trackIds[0].id;
  9. return id
  10. }).then(res=>{
  11. http(`song/url?id=${res}`).then(res=>{
  12. console.log(res)
  13. })
  14. })
  15. })
  16. </script>