27_Promise.html 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. </head>
  8. <body>
  9. <script src="./js/ajax.js"></script>
  10. <script>
  11. // Primise es6中提出的 异步优化处理方案
  12. // 一般用作于解决回调地狱问题(回调函数逐层嵌套带来的代码可读性差)
  13. // promise 会接收两个参数 一个是成功的回调函数 第二个是失败的回调函数
  14. // promise 对应两个回调函数 。then() 方法处理成功 和 catch() 方法处理失败。
  15. // new Promise(function(resolve,reject){
  16. // setTimeout(function(){
  17. // // resolve("成功");
  18. // reject("失败");
  19. // },1000)
  20. // }).then(function(res){
  21. // console.log(res);
  22. // }).catch(function(err){
  23. // console.log(err);
  24. // })
  25. // let pro1 = new Promise(function(resolve,reject){
  26. // setTimeout(function(){
  27. // resolve("成功");
  28. // },1000)
  29. // })
  30. // pro1.then(function(res){
  31. // console.log(res);
  32. // }).catch(function(err){
  33. // console.log(err);
  34. // })
  35. // let pro1 = new Promise(function(resolve,reject){
  36. // ajax("GET","./data/a.json",function(res){
  37. // resolve(res);
  38. // })
  39. // })
  40. // pro1.then(function(res){
  41. // console.log(res);
  42. // })
  43. // promise.all() 方法 接收一个数组参数 数组中包含多个promise对象
  44. // 只有当数组中的所有promise对象都成功时 才会调用then()方法
  45. // 只要有一个promise对象失败 就会调用catch()方法
  46. // let pro1 = new Promise(function(resolve,reject){
  47. // ajax("GET","./data/a.json",function(res){
  48. // reject(res);
  49. // })
  50. // })
  51. // let pro2 = new Promise(function(resolve,reject){
  52. // ajax("GET","./data/b.json",function(res){
  53. // resolve(res);
  54. // })
  55. // })
  56. // let pro3 = new Promise(function(resolve,reject){
  57. // ajax("GET","./data/c.json",function(res){
  58. // resolve(res);
  59. // })
  60. // })
  61. // 当所有promise对象都成功时 会返回一个数组 数组中包含所有promise对象的成功结果
  62. // Promise.all([pro1,pro2,pro3]).then(function(res){
  63. // console.log(res);
  64. // }).catch(function(err){
  65. // console.log(err);
  66. // })
  67. // Promise.race() 方法 接收一个数组参数 数组中包含多个promise对象
  68. // 如果第一个promise对象成功 就会调用then()方法
  69. // 如果第一个promise对象失败 就会调用catch()方法
  70. // Promise.race([pro1,pro2,pro3]).then(function(res){
  71. // console.log(res);
  72. // }).catch(function(err){
  73. // console.log("失败",err);
  74. // })
  75. // promise 有三种状态
  76. // 1. 等待状态(pending)
  77. // 2. 成功状态(fulfilled)
  78. // 3. 失败状态(rejected)
  79. // Promise.resolve() 方法 会返回一个成功的promise对象
  80. // Promise.reject() 方法 会返回一个失败的promise对象
  81. Promise.resolve("成功").then(function(res){
  82. console.log(res);
  83. })
  84. Promise.reject("失败").catch(function(err){
  85. console.log(err);
  86. })
  87. </script>
  88. </body>
  89. </html>