1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- </head>
- <body>
- <script>
- // setTimeout(function(){
- // console.log(1)
- // },1000)
- // Promise 他是一个异步优化解决方案 专门处理异步方法
- // Promise 有三种状态 pending fulfilled rejected
- // Promise 一旦状态改变 就不能再改变
- // Promise 有then方法 有catch方法
- // 接受两个参数 resolve(成功) reject(失败)
- // new Promise(function(resolve,reject){
- // setTimeout(function(){
- // resolve("hello")
- // },1000)
- // }).then(function(res){
- // console.log(res);
- // console.log("成功");
- // }).catch(function(){
- // console.log("错误");
- // })
- let pro1 = new Promise(function (resolve, reject) {
- setTimeout(function () {
- reject("第一个")
- },1000)
- })
- let pro2 = new Promise(function (resolve, reject) {
- setTimeout(function () {
- resolve("第二个")
- },2000)
- })
- let pro3 = new Promise(function (resolve, reject) {
- setTimeout(function () {
- resolve("第三个")
- },3000)
- })
- // Promise.all
- // 接受一个数组 数组中是promise对象
- // 如果数组中都是成功 就返回一个成功的数组
- // 如果数组中有一个失败 就返回一个失败的值
- // Promise.all 获取所有异步的结果如果都成功则算成功 如果有一个失败 就返回一个失败的值
- // Promise.all([pro1,pro2,pro3]).then(function (res) {
- // console.log(res);
- // }).catch(function (res) {
- // console.log(res);
- // console.log("错误");
- // })
- // Promise.race
- // 接受一个数组 数组中是promise对象
- // 如果数组中有一个成功 就返回一个成功的值
- // 如果数组中有一个失败 就返回一个失败的值
- // Promise.race 获取第一个异步的结果
- Promise.race([pro1,pro2,pro3]).then(function (res) {
- console.log(res);
- }).catch(function (res) {
- console.log(res);
- console.log("错误");
- })
- </script>
- </body>
- </html>
|