美文网首页
2021-04-16 js async和await的用法

2021-04-16 js async和await的用法

作者: 李先生1818 | 来源:发表于2021-04-16 16:38 被阅读0次

    1.含义和用法
    async 是一个修饰符,被它定义的函数会默认的返回一个 Promise 的 resolve的值。
    因此对 async 函数可以直接进行 then 操作,返回的值即为 then() 方法的传入函数。

    // demo
    async function demo_1() {
        console.log('a')
        return 1
    }
    demo_1().then(res => { 
      console.log(res)   //  a, 1,
    })  
    

    await同 async 一样,作为修饰符,但是它只能放在 async 内部使用。
    它是获取 Promise 中返回的内容, 即这个 Promise 函数中 resolve 或者 reject 的值。

    所以,async 用于申明一个 function 是异步的,而 await 用于等待一个异步方法执行完成。
    如下例:

    const myFun = function(){ return 'test'}
    
    async function demo_2() {
       const a = await 1
       const b = await new Promise((resolve, reject)=>{
            setTimeout(function(){
               resolve('wait')
            }, 3000)
       })
       const c = await myFun()
       console.log(a, b, c)
    }
    
    demo_2()
    
    /* 打印结果:
      3秒后输出:  1,"wait" ,"test",
     */
    

    2.应用
    比如说,这样一个场景:等待三个数据结果都返回,计算它们的和

    const myFun2 = function(val, time) {
        return new Promise((resolve, reject) =>{
            setTimeout(()=>{
                resolve(val)
            }, time)
        })
    }
    
    const demo_3 = async function() {
        let a = await myFun2(3, 5000)
        console.log(a)
        let b = await myFun2(4, 10000)
        console.log(b)
        let c =  await myFun2(5, 15000)
        console.log(c)
        let d = a + b +c  
        console.log(d)
    }
    
    demo_3()
    /* 打印结果:
      5秒后输出:  3
      10秒后输出:  4
      15秒后输出:  5 12
     */
    

    作者:逃避现实的豆

    漏控项目

    async initIndexSelect() {
          const res = await this.$axios.axios(
            "zoneLossController/queryZoneIndicatorDic.htm" +
              "?zoneType=" +
              (this.fenquTypeIndex + 1),
            {},
            "get"
          );
          this.$axios.axios(
            "zoneLossController/queryZoneIndicatorDic.htm" +
              "?zoneType=" +
              (this.fenquTypeIndex + 1),
            {},
            "get"
          );
          if (res.code == 0) {
            this.zhibiaoData = res.data;
          } else {
            uni.showToast({
              icon: "none",
              title: res.description,
            });
          }
        },
    

    import configInfo from './sysConfig.js';  
    let BASE_URL = "";
    let GIS_URL = "";
    
    export default{
        
        axios(url,data,method,json){
            return new Promise((resolve,reject)=>{
                
                configInfo.Pm.then((res) => {
                    BASE_URL = res.baseUrl
                    GIS_URL = res.gisBaseUrl
                    uni.setStorageSync('BASE_URL', BASE_URL);
                    uni.setStorageSync('GIS_URL', GIS_URL);
                    
                     uni.request({
                        url: BASE_URL + url,
                        method:method || 'GET',
                        data:data || {},
                        header:{
                            // 'Content-Type':'application/x-www-form-urlencoded',
                            'Content-Type':'application/json',
                            'Authorization':  uni.getStorageSync('SESSIONKEY')
                        },
                        xhrFields: {
                                    withCredentials: true
                                },
                        headers:{
                                    'X-Requested-With': 'XMLHttpRequest'
                                },
                        success:(res)=>{
                        
                            if (res.data.code >= 10000 && res.data.code < 11000) {
                                // 未登录,则返回登录界面
                                uni.navigateTo({
                                    url:'../../pages/login/login'
                                })
                                
                            }
                            resolve(res.data)
                        },
                        fail:(err)=>{
                            reject(err)
                        }
                    })
                    
                });
    
            })
        }
    }
    
        //示例
        // this.$axios.axios('leakageControlController/queryAlarmMessage.htm',obj,'post')
        //   .then((res)=>{
        //      if(res.code == 0){
        //      console.log('成功回调');
        //          }else{
        //              uni.showToast({
        //                icon: 'none',
        //                title: res.description
        //              });
        //          }
        //    })
        //    .catch((err)=>{
        //        console.log('错误回调');
        //    })
    

    相关文章

      网友评论

          本文标题:2021-04-16 js async和await的用法

          本文链接:https://www.haomeiwen.com/subject/dhbelltx.html