Only the first one works because you’re giving the return
in the first function, after that point what comes after is not executed. You can use the await
like you did in the first job and then give only one return
at the end of merging the data:
async asyncData() {
const {
data
} = await axios.get('/api/skills/view')
const response = await axios.get('/api/skills/5e5ff50f28767a288c6009ce')
return {
title: response.data.habilidade,
porcentagem: response.data.porcentagem,
skills: data
}
}
You can also unstructure the data:
async asyncData() {
const {
skills
} = await axios.get('/api/skills/view')
const response = await axios.get('/api/skills/5e5ff50f28767a288c6009ce')
const { habilidade: title, porcentagem } = response.data
return {
title,
porcentagem,
skills
}
}
const { habilidade: title, porcentagem } = response.data
takes the values habilidade
and porcentagem
of response.data
, note that in habilidade: title
I am renaming the value, creating a variable with the name of title
, in the end step the values as a result in a single object.
Note: No need to repeat the values in the object definition, so it already works as expected:
return {
title,
porcentagem,
skills
}
Another important detail, as you call it with await
, the code will only be executed after finishing the first request, the value of the second does not depend on the first, you can run both and return the value at the end:
const skillPromise = new Promise((resolve, reject) => {
resolve({
data: {
skills: ['skill1', 'skill 2']
}
})
})
const valuesPromise = new Promise((resolve, reject) => {
resolve({
data: {
habilidade: 'nome da habilidade',
porcentagem: 50
}
})
})
function asyncData() {
// const skillsPromise = axios.get('/api/skills/view')
// const valuesPromise = axios.get('/api/skills/5e5ff50f28767a288c6009ce')
Promise.all([skillPromise, valuesPromise]).then((results) => {
const onlyData = results.map(result => {
return result.data
})
const reducedObject = onlyData.reduce((result, current) => {
return Object.assign(result, current)
}, {})
/*
ou:
const reducedObject = Object.assign({}, ...onlyData)
*/
const {
habilidade: title,
porcentagem,
skills
} = reducedObject
console.log({
title,
porcentagem,
skills
})
})
}
asyncData()
I used the function Promise.all
passing the calls of axios
(in the example I needed to create the files only by demonstration), the Promise.all
returns an array with the results in case of success, as we only want the value of data
I make a map to pick up only this value, in the end I use it reduce
along with the Object.assign
to merge the data.
Boaa, I thought about making the change from Return to const, and I realized it was the Return msm hehe, Thanks!
– Josimara