My code is working. But I'm pretty sure that there is an easier way to do it. The way it is now, I can get the result I need by accessing the '_v' key inside my Promise. That's why I think I'm doing something wrong. Here is the code:
file1.js
import * as Utils from '../js/utils';
albumsArray() {
this.albums = Utils.getAlbums(this.user, this.token);
}
utils.js
export async function getAlbums(user, token){
let store = []
let data = await axios.get(`https://api.imgur.com/3/account/${user}/albums/`, {
headers: {
Authorization: `Bearer ${token}`,
Accept: 'application/json'
}
})
.then(response => {
response.data.data.map( data => store.push(data))
})
return store || [];
}
So, the way it is now, I get the result I want in the albums['_v'].
Obs: albums(this.albums) is a promise when I log it, and _v is the key where is the data I need. What I'm doing wrong. How can I make my code look better?
Thanks
The cool thing about async/await is that you get the actual value instead of the promise... You can do it like this:
export async function getAlbums(user, token){
let response = await axios.get(`https://api.imgur.com/3/account/${user}/albums/`, {
headers: {
Authorization: `Bearer ${token}`,
Accept: 'application/json'
}
})
return response.data.data || [];
}
You are pushing everything inside response.data.data into store... why not return response.data.data itself?
Then file1.js should also use async/await so you get the array instead of a promise...
async albumsArray() {
this.albums = await Utils.getAlbums(this.user, this.token);
}
Makes sense?