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);  
}  

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM