Vue JS-Helper Async Await函数用于获取返回未定义的数据
2022-05-10
4763
在 vuejs 中,我使用一个带有一些自定义函数的辅助文件,我将在项目中的任何地方使用这些自定义函数。
我正在重构一些异步等待承诺,但似乎无法解决它。
例如,我希望调用 fetchUserData(123),并将数据返回给方法。 虽然请求已发出并具有有效结果,但 userData const 未定义。
我做错了什么?
component.vue:这个打印出,Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'then')
import { currentDateTime , fetchUserData } from '@/helpers/util.js';
export default {
data () {
return {
userData: null,
loaded: false
}
},
methods : {
currentDateTime , fetchUserData ,
async setData () {
const userData = await fetchUserData(123)
userData.then(response => {
console.log(response) // prints undefined
this.loaded = true
this.userData.name = response.data.name
// other logic ...
})
}
},
created() {
this.setData()
}
}
component.vue:这个打印出,undefined
async setData () {
const userData = await fetchUserData(123)
console.log(userData )
}
util.js
import axios from 'axios';
export function capitalizeFirstLetter(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
export function zeroPad(num, places) {
return String(num).padStart(places, '0')
}
export function currentDateTime () {
const current = new Date()
const date = zeroPad ( current.getDate() , 2 ) + '/' + zeroPad( ( current.getMonth() + 1 ) , 2 ) + '/' + current.getFullYear()
const time = zeroPad ( current.getHours() , 2 ) + ":" + zeroPad ( current.getMinutes() , 2 ) + ":" + zeroPad ( current.getSeconds() , 2 )
const dateTime = date +' '+ time
return dateTime
}
export async function fetchUserData( id ) {
await axios.get('/data-table/' + id ).then(response=> {
console.log(response) // works
return response
}).catch(error => {
console.log(error)
});
}
2个回答
您的代码中出现了一些错误,解决方案如下:
component.vue
import { currentDateTime , fetchUserData } from '@/helpers/util.js';
export default {
data () {
return {
userData: null,
loaded: false
}
},
methods : {
currentDateTime , fetchUserData ,
async setData () {
const { data } = await fetchUserData(123);
this.loaded = true
this.userData.name = data.name
}
},
created() {
this.setData()
}
}
util.js
import axios from 'axios';
export async function fetchUserData(id) {
try {
const response = await axios.get('/data-table/' + id);
return response;
} catch (e) {
throw e;
}
}
Martinez
2022-05-10
关于承诺如何工作的一些困惑,请将您的代码更改为:
export function fetchUserData( id ) {
return axios.get('/data-table/' + id )
}
然后当您使用它时,切换到 try catch 就像您使用 async/await 一样
async setData () {
try {
const {data} = await this.fetchUserData(123)
this.userData.name = data.name
this.$nextTick(() => this.loaded = true)
} catch (err) {
// do something with err
}
}
Lawrence Cherone
2022-05-10