1、什么是Promise

1-1.then()方法

  1. <script>
  2. // promise
  3. /*
  4. 1、什么是promise 监听器
  5. */
  6. /*
  7. 怎么样实现一个promise new
  8. promise函数中传递两个参数
  9. resolve -->处理成功 then函数去触发resolve
  10. reject -->处理失败 catch函数去触发reject
  11. 这两个函数不会马上执行
  12. then和catch只会触发一个
  13. */
  14. var p = new Promise((resolve,reject)=>{
  15. resolve("success");
  16. reject("error")
  17. })
  18. console.log(p);
  19. p.then(res=>{
  20. console.log(res);
  21. })
  22. p.catch(res=>{
  23. console.log(res)
  24. })
  25. </script>

image.png

1-2.catch()方法

  1. <script>
  2. /* catch
  3. 1、resolve
  4. */
  5. var p = new Promise((resolve,reject)=>{
  6. // resolve("1");
  7. reject("2")
  8. })
  9. p.catch(res=>{
  10. console.log(res)
  11. })
  12. </script>

image.png

2、什么是回调地狱

两段http请求存在依赖,嵌套关系的时候就会造成回调地狱

  1. <script>
  2. /* 两段http请求存在依赖,嵌套关系的时候就会造成回调地狱 */
  3. var url = `http://47.108.197.28:3000/top/playlist`;
  4. $.ajax({
  5. url,
  6. success:res=>{
  7. var {name,coverImgUrl,id} = res.playlists[0];
  8. $("#name").html(name)
  9. $("img").attr("src",coverImgUrl)
  10. var url = `http://47.108.197.28:3000/playlist/detail?id=${id}`;
  11. $.ajax({
  12. url,
  13. success:res=>{
  14. var detail = res.playlist.description;
  15. $("#detail").html(detail)
  16. }
  17. })
  18. }
  19. })
  20. </script>

image.png

3、Promise解决

promise其实就是为了方便程序员阅读代码
本质上就是为了替代回掉函数的

  1. <script>
  2. /* promise其实就是为了方便程序员阅读代码
  3. 本质上就是为了替代回掉函数的
  4. */
  5. var url = `http://47.108.197.28:3000/top/playlist`;
  6. http(url).then(res=>{
  7. var id = res.playlists[0].id;
  8. return id;
  9. }).then(id=>{
  10. var url = `http://47.108.197.28:3000/playlist/detail?id=${id}`;
  11. http(url).then(res=>{
  12. console.log(res);
  13. })
  14. })
  15. </script>

image.png