在一個頁面中,有時會遇到多個ajax請求 同時發生,這樣不能保證它們的運行順序,會導致數據出錯,
如果有loading動畫時,你不能保證哪個請求先完成,來結束動畫。
如果兩個數據有關聯,必須先完成哪個再執行下一個,可以這樣來操作。
可以看到上面的代碼是一個相對簡單的promise結構。
我們先new promise,在參數列表有兩個參數,一個resolve一個rejects。通俗的來講,
resolve相當於ajax中的success,rejects則就是catch。當然,這兩個單詞可以隨便取,也可以在參數列表寫上a,b。但是他們代表的意思是一模一樣的。在后面我們可以看到一行代碼“resolve()”,這就相當於return。
在promise里面的代碼塊會最先執行,然后resolve(),接着會運行then里面的方法。
在then里面也有參數,()=> {/代碼塊/},因為我在上面代碼中resolve()的括號中並沒有寫參數,所以可以看成它返回的是一個空的結果集,所以我在then后面有()來接受,因為是空結果集,所以我用()來接收。
當然你也可以返回想要的結果,打個比方,我把代碼改成下面這樣
我讓resolve返回了一個值,然后在then里面打印出來。
可以看到,res被打印出來就是返回的值1。
Promise.all() :
created(){ this.init() }, methods: { init () { this.$store.dispatch('setLoading', true) const Ajax = new Promise((resolve, reject) => { getAllRecruiter().then(res => { this.recruiter.option = res.data this.recruiter.val = res.data[0] resolve(res) // 請求成功后,利用resolve改變promise狀態,並且作為返回值傳回到promise對象 }).catch((err) => { reject(err); // 請求失敗則利用reject改變狀態,終止當前函數流 }) }) const Ajax0 = new Promise((resolve, reject) => { getAllEmploymentType().then(res => { this.employmentType.option = res.data resolve() }).catch(() => { }) }) const Ajax1 = new Promise((resolve, reject) => { getAllLevel().then(res => { this.careerLevel.option = res.data resolve() }).catch(() => { }) }) const Ajax2 = new Promise((resolve, reject) => { getAllBenefit().then(res => { this.benefits.option = res.data resolve() }).catch(() => { }) }) Promise.all([Ajax, Ajax0, Ajax1, Ajax2]).then(() => { //所有請求都成功后執行函數 this.getOldData() }).catch(() => { //// 異常處理 this.$store.dispatch('setLoading', false) }) } }
-----------------------------
部分文章來自:https://blog.csdn.net/qq_39861508/article/details/78925118