微信小程序異步回調

場景以下:現有一個方法須要等待其餘N個異步函數執行完畢後執行,callback麻煩的頭大,翻了一波API原來小程序已經支持 async函數,那一切就好辦了。ajax

第一步:打開加強編譯小程序

 

 

 第二部:直接擼代碼,這裏寫了個🌰異步

  wait:function() {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve('ajax請求等待')
            }, 2000)
        })
    },
    onLoad: async function(options) {
        let ajaxTime = await this.wait();
        console.log(ajaxTime)
        let getIndex = this.getArrIndex(this.data.sexArray, 'other.其餘');
        console.log('異步執行後獲取index:'+getIndex)
        this.setData({
            sexindex: getIndex
        })
    },

上面的執行順序是:async

先執行:this.wait(),進入函數體,而後進入等待函數


2秒後執行:console.log(ajaxTime)this


下面的代碼則按照基本的js執行順序執行。spa

相關文章
相關標籤/搜索