27_promise.html 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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>
  10. // setTimeout(function(){
  11. // console.log(1)
  12. // },1000)
  13. // Promise 他是一个异步优化解决方案 专门处理异步方法
  14. // Promise 有三种状态 pending fulfilled rejected
  15. // Promise 一旦状态改变 就不能再改变
  16. // Promise 有then方法 有catch方法
  17. // 接受两个参数 resolve(成功) reject(失败)
  18. // new Promise(function(resolve,reject){
  19. // setTimeout(function(){
  20. // resolve("hello")
  21. // },1000)
  22. // }).then(function(res){
  23. // console.log(res);
  24. // console.log("成功");
  25. // }).catch(function(){
  26. // console.log("错误");
  27. // })
  28. let pro1 = new Promise(function (resolve, reject) {
  29. setTimeout(function () {
  30. reject("第一个")
  31. },1000)
  32. })
  33. let pro2 = new Promise(function (resolve, reject) {
  34. setTimeout(function () {
  35. resolve("第二个")
  36. },2000)
  37. })
  38. let pro3 = new Promise(function (resolve, reject) {
  39. setTimeout(function () {
  40. resolve("第三个")
  41. },3000)
  42. })
  43. // Promise.all
  44. // 接受一个数组 数组中是promise对象
  45. // 如果数组中都是成功 就返回一个成功的数组
  46. // 如果数组中有一个失败 就返回一个失败的值
  47. // Promise.all 获取所有异步的结果如果都成功则算成功 如果有一个失败 就返回一个失败的值
  48. // Promise.all([pro1,pro2,pro3]).then(function (res) {
  49. // console.log(res);
  50. // }).catch(function (res) {
  51. // console.log(res);
  52. // console.log("错误");
  53. // })
  54. // Promise.race
  55. // 接受一个数组 数组中是promise对象
  56. // 如果数组中有一个成功 就返回一个成功的值
  57. // 如果数组中有一个失败 就返回一个失败的值
  58. // Promise.race 获取第一个异步的结果
  59. Promise.race([pro1,pro2,pro3]).then(function (res) {
  60. console.log(res);
  61. }).catch(function (res) {
  62. console.log(res);
  63. console.log("错误");
  64. })
  65. </script>
  66. </body>
  67. </html>