日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 Vue 正文

Vue中的同步和異步調用順序詳解_vue.js

作者:neoeson ? 更新時間: 2022-04-06 Vue

Vue的同步和異步調用順序

Vue中的方法調用順序是依次進行的,方法體內部也是依次執行的,但是,兩個方法體的執行順序并不能嚴格控制。

以下方法中都帶有promise函數或異步調用。

?? ?initUserData() {
?? ? ?this.getPsCountryList() // 1 獲取國家列表stateOptions,方法內同步
?? ? ?this.getTimeZone() // 2 獲取時區timezones,方法內同步
?? ? ?this.getUserInfo() // 3 獲取用戶信息
?? ?}

在實際運行中,三個方法的執行順序是1-2-3,但是方法3始終不能獲取到stateOptions和timezones

背后的調用順序是1-2-3,但是,方法的執行時間并沒有嚴格控制。

如果想要做到方法調用和執行是同步的,可以使用async和await修飾符。

例如

?? ?async initUserData() {
?? ? ?await this.getPsCountryList() // 1 獲取國家列表stateOptions,方法內同步
?? ? ?await this.getTimeZone() // 2 獲取時區timezones,方法內同步
?? ? ?await this.getUserInfo() // 3 獲取用戶信息
?? ?}

Vue兩個異步方法順序執行

需求:兩個異步函數按順序執行,首先獲取第一個異步函數的返回的值,接著在第二個異步函數里面調用

方法:先在第一個異步函數里返回一個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()
?? ??? ?},

原文鏈接:https://blog.csdn.net/alan_alei/article/details/96995147

欄目分類
最近更新