veu axios 中 async + await 使用
01) 使用 await
等待網路請求返回后,才執行后面其他代碼
methods: { // 圖書詳細 async cliDetail() { console.log("本方法開始執行__",new Date().toLocaleTimeString()); await this.$get(this.$interfacres.getBookDetail, {bookId: 3}).then(res => { console.log("await 網路請求返回",new Date().toLocaleTimeString(), res); }); console.log("我是daFei_test",new Date().toLocaleTimeString()); } }
01-2) 使用 await
async cliDetail2() { const bookDetail = await this.$get(this.$interfacres.getBookDetail, {bookId: 3}) console.log(bookDetail); // 接口返回的數據都在這里 }
02) 沒有使用 await
如果網絡延遲,后面代碼照常執行
methods: { // 圖書詳細 async cliDetail() { console.log("本方法開始執行__",new Date().toLocaleTimeString()); this.$get(this.$interfacres.getBookDetail, {bookId: 3}).then(res => { console.log("網路請求返回",new Date().toLocaleTimeString(), res); }); console.log("我是daFei_test",new Date().toLocaleTimeString()); } }
03) 對比