-1

I am using the lorem picsum api with axios.

const axios = require('axios').default;
const imageArray = async () => {
    try {
        const list = await axios.get('https://picsum.photos/v2/list?page=2&limit=50');
        const data = await list.data;
        console.log(data);
        return data;
    } catch (err) {
        console.log(err);
    }
}
const imageList = imageArray();
console.log(imageList);

https://picsum.photos/v2/list?page=2&limit=50 this url returns an array of 50 objects named data. I want to assign this array to imageList.

console.log(data) gives the following output.

[
  {
    id: '1047',
    author: 'sergee bee',
    width: 3264,
    height: 2448,
    url: 'https://unsplash.com/photos/bIQiMWxX_WU',
    download_url: 'https://picsum.photos/id/1047/3264/2448'
  },
  {
    id: '1048',
    author: 'Anthony DELANOIX',
    width: 5616,
    height: 3744,
    url: 'https://unsplash.com/photos/b5POxb2aL9o',
    download_url: 'https://picsum.photos/id/1048/5616/3744'
  },.....
......
....]

But console.log(imageList) returns Promise { <pending> } and no other error. From the log i understand that the output is called before promise is completed. But i don't get why this happens because the function i am calling is already an async function. so it must await.

pls help me. sorry if this question was silly.

1 Answers1

0

It's because you're missing await in

const imageList = imageArray();

Try to change it into

((async () => {
    const imageList = await imageArray();
    console.log(imageList);
})());

and run again

Albert Suteja
  • 81
  • 1
  • 4