Vue.js中Promise、异步、同步、定时器

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

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

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

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

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方法

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只在指定时间后执行一次,代码如下:

<script>  
//定时器 异步运行  
function hello(){  
alert("hello");  
}  
//使用方法名字执行方法  
var t1 = window.setTimeout(hello,1000);  
var t2 = window.setTimeout("hello()",3000);//使用字符串执行方法  
window.clearTimeout(t1);//去掉定时器  
</script>   

定时器(2)

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

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

  

猜你喜欢

转载自www.cnblogs.com/gaofz/p/11935176.html