Express 如何在不使用异步/等待的情况下编写函数?
我具有以下功能: 我正在学习MEVN。我想知道是否有必要在不使用async/await的情况下编写相同的函数。我目前提出了以下建议:Express 如何在不使用异步/等待的情况下编写函数?,express,vue.js,async-await,Express,Vue.js,Async Await,我具有以下功能: 我正在学习MEVN。我想知道是否有必要在不使用async/await的情况下编写相同的函数。我目前提出了以下建议: methods: { getPost () { const response = PostsService .getPost({ id: this.$route.params.id }) this.title = response.data.title this.description = response.
methods: {
getPost () {
const response = PostsService
.getPost({
id: this.$route.params.id
})
this.title = response.data.title
this.description = response.data.description
//this.$router.push({ name: 'Posts' })
},
但我在控制台日志中得到一个错误,上面写着:挂载钩子中的错误:“TypeError:response.data未定义”。任何帮助都将不胜感激。它看起来像是
PostsService
扩展了axios,因此您可以将其用作承诺:
methods: {
getPost () {
PostsService
.getPost({
id: this.$route.params.id
})
.then(({data}) => {
this.title = data.title
this.description = data.description
this.$router.push({ name: 'Posts' })
}
},
错误的原因是
response=PostsService.getPosts()
实际上没有用数据填充响应变量。它必须首先运行查询,然后您可以在中的回调中访问它。然后()
这就是您不希望使用异步等待
语法的原因吗?出于某些原因,它不适用于我版本的webpack。我同意Jeff的观点。响应
未定义,因为PostsService.getPost()
是一个异步请求,您必须等待它解析(或拒绝)后才能访问响应内容。对于此请求引发的错误,您可以在then()
案例之后使用catch()
块捕获它们。谢谢,这是一个快速修复!
methods: {
getPost () {
PostsService
.getPost({
id: this.$route.params.id
})
.then(({data}) => {
this.title = data.title
this.description = data.description
this.$router.push({ name: 'Posts' })
}
},