zoukankan      html  css  js  c++  java
  • Vue.js中Promise、异步、同步、定时器

    Vue.js使用Axios或Ajax请求后台时,是异步请求,所有的请求同时执行,后面的then随机执行

    要想实现同步执行可以使用await和async

    在需要同步执行(即后面一个方法的参数是前一个方法的返回值),在父层方法前面加async,并且在字层方法前面加await,

    然后方法中需返回Promise对象,用resolve()表示执行成功,

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    async mounted() {
        this.currentTime = parseTime(
          new Date().toString(),
          '{y}-{m}-{d} {h}:{i}:{s}'
        )
        await this.getOrgs()
        await this.getQuDao()
        await this.getProductList()
        await this.queryData()
      },
     
    getOrgs() {
      return newPromise((resolve,reject) => {
         ...
         resolve(true)
      }) 
    }
    getQuDao() {
      return newPromise((resolve,reject) => {
         ...
         resolve(true)
      }) 
    }
    ...

    当需要等到所有的请求都成功完成请求数据,再做其他操作时可以用到Promise.All方法

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    initPage() {
      const _amt = this.getData()
      ...
      Promise.all([
            _amt,_amtPie,
            _amtRepay,_repayAmtPie,
            _num,_intoPie,
            _rate,_rateBar,
            _map,_table
          ]).then(([_amt, _amtPie, _amtRepay, _repayAmtPie, _num, _intoPie, _rate,
      _rateBar, _map, _table]) => {
          ...
          })
          .catch(() => {
           ...
          })
    }
    getData() {
      return new Promise((resolve,reject) => {
        gethttpData({}).then(response => {
           ... 
         }).catch(err => {
           ...
          })
      }) 
    }

      

    定时器(1)

    setTimeout只在指定时间后执行一次,代码如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    <script> 
    //定时器 异步运行 
    function hello(){ 
    alert("hello"); 
    //使用方法名字执行方法 
    var t1 = window.setTimeout(hello,1000); 
    var t2 = window.setTimeout("hello()",3000);//使用字符串执行方法 
    window.clearTimeout(t1);//去掉定时器 
    </script>  

    定时器(2)

    setInterval以指定时间为周期循环执行,代码如下:

    1
    2
    3
    4
    5
    6
    //实时刷新时间单位为毫秒 
    setInterval('refreshQuery()',8000);  
    /* 刷新查询 */ 
    function refreshQuery(){ 
       $("#mainTable").datagrid('reload',null); 

      

  • 相关阅读:
    两个链表的第一个公共结点
    数组中的逆序对
    C++强制类型转换运算符(static_cast、reinterpret_cast、const_cast和dynamic_cast)
    第一个只出现一次的字符
    机器学习算法速览表
    丑数
    设计模式---行为型设计模式【策略模式】
    设计模式---行为型设计模式【备忘录模式】
    设计模式----创建型设计模式【单例模式】
    设计模式----创建型设计模式【简单工厂、工厂方法、抽象工厂】
  • 原文地址:https://www.cnblogs.com/zjw2004112/p/12974148.html
Copyright © 2011-2022 走看看