您的位置:首页 > 博客中心 > 前端开发 >

js中Promise简单使用

时间:2022-04-11 14:44

<script >         //定义一个返回Promise对象方法      const getlist=((type)=>{                  //resolve表示完成操作         //reject异常操作         return  new Promise((resolve,reject)=>{

 

            // throw{             //             name:‘typeErr‘,             //             message:‘you should enter a number‘             //         }           if(type==1){           resolve(‘错误啦。。。‘)}           else{           reject(‘对啦。。。‘)         } })      })         window.onload=( ()=>{                          //noawait();              yawait();         })                  //不用await         const noawait=(()=>{            getlist(2).then((result)=>{             console.log(‘result‘);             console.log(result);            }).catch((err)=>{             console.log(‘err me‘);              console.log(err);            })         })       //使用await方式接收         const yawait=(async ()=>{           try {           await只接受resolve返回的内容             let data =await getlist(1);            console.log(data);           } catch (error) {            reject返回的需要在catch里进行捕捉               console.log(error);           }            

 

        })     </script>

本类排行

今日推荐

热门手游