Refactor story detail view to use async/await.

This commit is contained in:
Jack Coldrick 2020-05-02 21:10:42 +01:00
parent 3d8a0dff6e
commit b63dd127ae

View File

@ -41,7 +41,7 @@ import axios from 'axios'
export default {
name: 'StoryDetailView',
data: function () {
data () {
return {
creator: {},
events: [],
@ -50,42 +50,31 @@ export default {
projects: []
}
},
created: function () {
created () {
this.getStory(this.$route.params.id)
},
methods: {
getStory: function (storyId) {
const vm = this
async getStory (storyId) {
const baseUrl = 'http://localhost:8080/v1'
axios.get(`${baseUrl}/stories/${storyId}`)
.then(function (response) {
vm.story = response.data
axios.get(`${baseUrl}/users/${vm.story.creator_id}`)
.then(function (response) {
vm.creator = response.data
})
})
axios.get(`${baseUrl}/stories/${storyId}/tasks`)
.then(function (response) {
const tasks = response.data
vm.tasks = tasks
const { data: story } = await axios.get(`${baseUrl}/stories/${storyId}`)
this.story = story
const { data: creator } = await axios.get(`${baseUrl}/users/${this.story.creator_id}`)
this.creator = creator
const { data: tasks } = await axios.get(`${baseUrl}/stories/${storyId}/tasks`)
this.tasks = tasks
const requests = []
tasks.reduce(function (acc, task) {
if (!acc.includes(task.project_id)) {
acc.push(task.project_id)
requests.push(axios.get(`${baseUrl}/projects/${task.project_id}`))
}
return acc
}, [])
Promise.all(requests).then(responses => {
vm.projects = responses.map(response => response.data)
})
})
axios.get(`${baseUrl}/events?story_id=${storyId}`)
.then(function (response) {
vm.events = response.data
})
const requests = []
tasks.reduce((acc, task) => {
if (!acc.includes(task.project_id)) {
acc.push(task.project_id)
requests.push(axios.get(`${baseUrl}/projects/${task.project_id}`))
}
return acc
}, [])
this.projects = (await Promise.all(requests)).map(response => response.data)
const { data: events } = await axios.get(`${baseUrl}/events?story_id=${storyId}`)
this.events = events
}
}
}