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

  

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM