我试图从服务的axios响应中返回数据,但是我将始终从服务undefined
接收数据,但是在服务内部我有数据。你能告诉我我在做什么错吗?
这是我的服务的样子:
import axios from 'axios';
export default {
async fetchById (articleId) {
await axios.post('/api/article', { id: articleId })
.then(function (response) {
console.log('axios', response) // valid response
return response.data
})
.catch(function (e) {
console.error('error', e);
});
}
}
在组件中有我的用法:
async created () {
const article = await articleService.fetchById('12345')
console.log('article', article) // there I have undefined
}
答案 0 :(得分:5)
您缺少返回声明
import axios from 'axios';
export default {
async fetchById (articleId) {
// Missing `return` in the next line
return await axios.post('/api/article', { id: articleId })
.then(function (response) {
console.log('axios', response) // valid response
return response.data
})
.catch(function (e) {
console.error('error', e);
});
}
}
我鼓励您开始使用TypeScript,通过为函数进行正确的键入可以轻松避免此类错误。
答案 1 :(得分:2)
在第一个示例中,您只能使用async/await
然后返回结果:
import axios from 'axios';
export default {
async fetchById (articleId) {
try{
const response= await axios.post('/api/article', { id: articleId })
return response.data
}catch(e){
console.error('error', e);
return null;
};
}
}
答案 2 :(得分:0)
您可以使用callback()函数。这是当您将函数作为参数传递给现有函数时,它将在axios调用完成后执行。这是与您的代码一起使用的方式:
async fetchById (articleId) {
await axios.post('/api/article', { id: articleId })
.then(function (response) {
console.log('axios', response) // valid response
callback(response.data)
})
.catch(function (e) {
console.error('error', e);
});
}