Vue中的同步和異步調用順序詳解
Vue的同步和異步調用順序
Vue中的方法調用順序是依次進行的,方法體內部也是依次執(zhí)行的,但是,兩個方法體的執(zhí)行順序并不能嚴格控制。
以下方法中都帶有promise函數(shù)或異步調用。
?? ?initUserData() {
?? ? ?this.getPsCountryList() // 1 獲取國家列表stateOptions,方法內同步
?? ? ?this.getTimeZone() // 2 獲取時區(qū)timezones,方法內同步
?? ? ?this.getUserInfo() // 3 獲取用戶信息
?? ?}在實際運行中,三個方法的執(zhí)行順序是1-2-3,但是方法3始終不能獲取到stateOptions和timezones
背后的調用順序是1-2-3,但是,方法的執(zhí)行時間并沒有嚴格控制。
如果想要做到方法調用和執(zhí)行是同步的,可以使用async和await修飾符。
例如
?? ?async initUserData() {
?? ? ?await this.getPsCountryList() // 1 獲取國家列表stateOptions,方法內同步
?? ? ?await this.getTimeZone() // 2 獲取時區(qū)timezones,方法內同步
?? ? ?await this.getUserInfo() // 3 獲取用戶信息
?? ?}Vue兩個異步方法順序執(zhí)行
需求:兩個異步函數(shù)按順序執(zhí)行,首先獲取第一個異步函數(shù)的返回的值,接著在第二個異步函數(shù)里面調用
方法:先在第一個異步函數(shù)里返回一個promise,接著用async和await調用它
第一個異步方法
getAllNotice() {
?? ??? ??? ??? ?let data = {
?? ??? ??? ??? ??? ?"searchParams": [{
?? ??? ??? ??? ??? ??? ?"fieldName": "equipmentId",
?? ??? ??? ??? ??? ??? ?"operate": "eq",
?? ??? ??? ??? ??? ??? ?"value": "000000"
?? ??? ??? ??? ??? ?}],
?? ??? ??? ??? ??? ?"size": -1
?? ??? ??? ??? ?}
?? ??? ??? ??? ?return new Promise((resolve) => {
?? ??? ??? ??? ??? ?API.getNotice(data).then(res => {
?? ??? ??? ??? ??? ??? ?console.log(res)
?? ??? ??? ??? ??? ??? ?if (res.data.code == "200") {
?? ??? ??? ??? ??? ??? ??? ?this.noticeList = res.data.data.list
?? ??? ??? ??? ??? ??? ??? ?console.log(this.noticeList)
?? ??? ??? ??? ??? ??? ??? ?resolve();
?? ??? ??? ??? ??? ??? ??? ?return
?? ??? ??? ??? ??? ??? ?} else {
?? ??? ??? ??? ??? ??? ??? ?uni.showToast({
?? ??? ??? ??? ??? ??? ??? ??? ?title: res.data.message,
?? ??? ??? ??? ??? ??? ??? ??? ?duration: 1000,
?? ??? ??? ??? ??? ??? ??? ??? ?icon: "none"
?? ??? ??? ??? ??? ??? ??? ?})
?? ??? ??? ??? ??? ??? ?}
?? ??? ??? ??? ??? ?})
?? ??? ??? ??? ?})?? ??? ??? ??? ?
?? ??? ??? ?},第二個異步方法
//獲得當前的公告列表
?? ??? ??? ?getNowNotice(){
?? ??? ??? ??? ?//獲取當前時間戳
?? ??? ??? ??? ?var timestamp = (new Date()).getTime();
?? ??? ??? ??? ?var _this = this
?? ??? ??? ??? ?console.log(timestamp);
?? ??? ??? ??? ?//將noticeList的結束時間轉換成時間戳
?? ??? ??? ??? ?for(var i=0; i<this.noticeList.length; i++){
?? ??? ??? ??? ??? ?var endTimeStamp = TIME.TimeToTimeStamp(this.noticeList[i].endTime)
?? ??? ??? ??? ??? ?console.log(endTimeStamp)
?? ??? ??? ??? ??? ?if(endTimeStamp>timestamp){
?? ??? ??? ??? ??? ??? ?_this.noticeNewList.push(this.noticeList[i])
?? ??? ??? ??? ??? ?}
?? ??? ??? ??? ?}
?? ??? ??? ??? ?console.log("noticeNewList",_this.noticeNewList)
?? ??? ??? ?}用async和await
async onLoad(option) {
?? ??? ??? ?await this.getAllNotice()
?? ??? ??? ?await this.getNowNotice()
?? ??? ?},以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Vue?3?表單與后端數(shù)據(jù)交互之查詢并回顯數(shù)據(jù)步驟流程
本文給大家介紹Vue3表單與后端數(shù)據(jù)交互之查詢并回顯數(shù)據(jù)步驟流程,結合實例代碼給大家介紹的非常詳細,感興趣的朋友跟隨小編一起看看吧2024-12-12
vue 實現(xiàn)LED數(shù)字時鐘效果(開箱即用)
這篇文章主要介紹了vue 實現(xiàn)LED數(shù)字時鐘效果(開箱即用),每一個數(shù)字由七個元素構成,即每一個segment元素,本文給大家分享實現(xiàn)實例,感興趣的朋友一起看看吧2019-12-12

