JS 异步编程与Promise,还有async与await实例

  • A+
所属分类:Web前端
摘要

异步加载图片体验js任务操作:  定时器的任务轮询: 通过文件依赖了解任务排序:

异步加载图片体验js任务操作:

    <script>         function loadImg(src, resolve, reject) {             let img = new Image();             img.src = src;             img.onload = () => {                 resolve(img);             };             img.onerror = reject;         }         loadImg('images/1.jpg', img => {             console.log('加载成功~');             document.body.append(img);         }, () => {             console.log('加载失败~');         })     </script>

JS 异步编程与Promise,还有async与await实例

 

 

定时器的任务轮询:

<!doctype html> <html lang="zh-cn">  <head>     <meta charset="utf-8">     <style>         div {             width: 100px;             height: 100px;             background: lightgreen;             position: absolute;             top: 0;             left: 0;         }     </style> </head>  <body>     <div></div>      <script>         function interval(callback, delay = 100) {             let id = setInterval(() => callback(id), delay);         }         interval((id) => {             let div = document.querySelector('div');             let left = window.getComputedStyle(div).left == 'auto' ? 0 : parseInt(window.getComputedStyle(div).left);              div.style.left = left + 10 + 'px';             if (left >= 200) {                 clearInterval(id);                  interval((id) => {                     let width = parseInt(window.getComputedStyle(div).width);                     div.style.width = width - 10 + 'px';                     if (width <= 20) {                         clearInterval(id);                     }                 })             }         });     </script> </body>  </html>

 

通过文件依赖了解任务排序:

    <script>         // 先走主进程,再执行队列         function load(src, resolve) {             let script = document.createElement('script');             script.src = src;             script.onload = resolve;             document.body.append(script);         }         load('js/func.js', () => {             func();              load('js/func2.js', () => {                 func2();             });          });          console.log('我在执行了~');     </script>

 

Promise微任务处理机制:

    <script>         //pending准备阶段         // console.log(new Promise((resolve, reject) => { }))           //fulfilled         // console.log(new Promise((resolve, reject) => {         //     resolve('成功');         // }));           //rejected         // console.log(new Promise((resolve, reject) => {         //     reject('失败');         // }));           new Promise((resolve, reject) => {             resolve('成功');             // reject('失败');         }).then(data => {             console.log('成功');         }, error => {             console.log('失败');         }).then(data => {             console.log('成功2');         }, error => {             console.log('失败2');         });     </script>

 

宏任务与微任务执行顺序:

    <script>         setTimeout(() => {             console.log('这是异步任务--宏任务,最后执行');         }, 0);          new Promise((resolve, reject) => {             resolve();              // 这是同步任务             console.log('这是Promise里的同步任务');          }).then(data => {             console.log('这是异步任务--微任务');         });          console.log('这是普通同步任务');     </script>

JS 异步编程与Promise,还有async与await实例

 

promise单一状态与状态中转:

    <script>         let p = new Promise((resolve, reject) => {             setTimeout(function () {                 reject('失败---');                  resolve('此时成功是无效的,因为状态不可逆');             }, 2000)         });          new Promise((resolve, reject) => {             // 状态中转,以传递过来的结果为准             resolve(p);         }).then(res => {             console.log('成功' + res);         }, err => {             console.log('失败' + err);         });     </script>

 

了解Promise.then的基本语法:

    <script>          // new Promise((resolve, reject) => {         //     resolve('买了一瓶可乐');         // }).then(res => {         //     console.log(res);         // }, err => {         //     console.log(err);         // });           //只传递成功的状态         // new Promise((resolve, reject) => {         //     resolve('买了一瓶可乐');         // }).then(res => {         //     console.log(res);         // });           //只传递失败的状态         // new Promise((resolve, reject) => {         //     reject('涨价了,买不起');         // }).then(null, err => {         //     console.log(err);         // });           //多次传递         new Promise((resolve, reject) => {             reject('涨价了,买不起');         }).then(null, err => {             console.log(err);         }).then(null, err => {             console.log(err);         });     </script>

 

promise then 也是一个promise

    <script>          // let p1 = new Promise((resolve, reject) => {         //     resolve('fufilled');         // });          // // .then返回的也是一个promise         // let p2 = p1.then(         //     success => console.log(success),         //     err => console.log(err),         // );          // console.log(p1); // (已完成状态)         // console.log(p2); // 添加到微任务里,还没有处理(是准备状态)          // //宏任务         // setTimeout(function () {         //     console.log(p1); // (已完成状态)         //     console.log(p2); // 由于微任务执行早于宏任务,因此当执行到宏任务时,微任务已经执行完毕(是已完成状态)         // });            let p1 = new Promise((resolve, reject) => {             reject('error');         });          // .then返回的也是一个promise         let p2 = p1.then(             success => console.log(success),             err => console.log(err),         ).then(             success => console.log('上一步操作完成'),             err => console.log('上一步操作失败'),         );     </script>

 

then返回值的处理技巧:

    <script>          // 第一次then返回具体的值         // let p1 = new Promise((resolve, reject) => {         //     resolve('success');         // }).then(         //     success => 'cyy',         //     err => console.log(err),         // ).then(         //     value => console.log(value),         //     err => console.log(err),         // );           // 第一次then返回promise状态         let p1 = new Promise((resolve, reject) => {             resolve('success');         }).then(             success => {                 return new Promise((resolve, reject) => {                     reject('失败了呀~');                 });             },             err => console.log(err),         ).then(             value => console.log(value),             err => console.log(err),         );     </script>

 

其他类型的promise封装:

    <script>          // 如果第一次的then返回值是对象,并且含有then方法,那么会被封装成promise返回         // let p1 = new Promise((resolve, reject) => {         //     resolve('success');         // }).then(         //     success => {         //         return {         //             then(resolve, reject) {         //                 resolve('我被封装成promise啦');         //             }         //         }         //     },         //     err => console.log(err),         // ).then(         //     value => console.log(value),         //     err => console.log(err),         // );           // 如果第一次的then返回值是类,并且含有then方法,那么会被封装成promise返回         // let p1 = new Promise((resolve, reject) => {         //     resolve('success');         // }).then(         //     success => {         //         class Func {         //             then(resolve, reject) {         //                 resolve('我被封装成promise啦');         //             }         //         }         //         return new Func();         //     },         //     err => console.log(err),         // ).then(         //     value => console.log(value),         //     err => console.log(err)         // );           // 如果第一次的then返回值是类的静态方法then,那么会被封装成promise返回         let p1 = new Promise((resolve, reject) => {             resolve('success');         }).then(             success => {                 return class Func {                     static then(resolve, reject) {                         resolve('我被封装成promise啦');                     }                 };             },             err => console.log(err),         ).then(             value => console.log(value),             err => console.log(err)         );     </script>

 

使用promise封装ajax异步请求:

   <script>         function request(url) {             return new Promise((resolve, reject) => {                 let xhr = new XMLHttpRequest();                 xhr.open(url, 'GET');                 xhr.send();                 xhr.onload = function () {                     if (this.status == 200) {                         resolve(JSON.Parse(this.response));                     } else {                         reject('加载失败');                     }                 }                 xhr.onerror = function () {                     reject(this);                 }             });         }          let url = `http://localhost:8080`;         request(`${url}/user.php?name='cyy'`).then(user => {             return request(`${url}/info.php?uid=${user.id}`);         }).then(lesson => {             console.log(lesson);         });     </script>

 

promise多种错误检测与catch使用:

    <script>         //reject返回Error         // new Promise((resolve, reject) => {         //     reject(new Error('error错误'));         // }).then(val => {         //     console.log(val);         // }, err => {         //     console.log(err);         // });          // new Promise((resolve, reject) => {         //     reject(new Error('error错误'));         // }).then(val => {         //     console.log(val);         // }, err => {         //     console.log(err.message);         // });           // 直接抛出异常         // new Promise((resolve, reject) => {         //     throw new Error('抛出异常');         // }).then(val => {         //     console.log(val);         // }, err => {         //     console.log(err);         // });           // 自动抛出异常         // new Promise((resolve, reject) => {         //     cyy + 1;         // }).then(val => {         //     console.log(val);         // }, err => {         //     console.log(err);         // });           // catch捕获异常         new Promise((resolve, reject) => {             reject('失败啦');         }).then(val => {             console.log(val);         }).catch(err => {             console.log(err);         });      </script>