0

I have developed a code to fetch the image information of an object inside a loop statement. However, when I print the output at the bottom of the loop, it is empty. Can anyone help me with this, please? The getMediaInfo function is an Axios call.

    const postsWithImageURLS = [];
    res.data.forEach(async (post) => {
        const response = await getMediaInfo(post.featured_media);
        postsWithImageURLS.push({...post, featured_url: response});
    });
    console.log(postsWithImageURLS);
user435245
  • 859
  • 4
  • 16
  • 28
  • Your array `postsWithImageURLS` is declared as an empty array. You're not pushing any data into it. – Al Duncanson May 12 '21 at 13:15
  • I have fixed the code, even by pushing it into the array the value does not change after the loop – user435245 May 12 '21 at 13:17
  • I suggest you read through this first. https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call/14220323#14220323 – Nisanth Reddy May 12 '21 at 13:18
  • Does this answer your question? [Using async/await with a forEach loop](https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop) – Henry Ecker May 12 '21 at 13:19

2 Answers2

2
 Promise.all(res.data.map(async (post) => {
    if (post.categories.includes(NEWS_CATEGORY_ID)) {
        const response = await getMediaInfo(post.featured_media);
        post = {...post, featured_url: response};
        return post;
    }
})).then(postsWithImageURLS => console.log(postsWithImageURLS));

You should access postsWithImageURLS after all async methods finish.

SwishSwish
  • 158
  • 7
  • You suggested using a `map` instead of a `forEach`. This leads to many null entries since I have implemented an `if` statement. Do you have any suggestions on how to fix this? – user435245 May 12 '21 at 13:28
  • You may exclude null or undefined element from array `postsWithImageURLS ` using array's `filter` method like this: `then(postsWithImageURLS => postsWithImageURLS.filter(v => !!v)).then(console.log)` – SwishSwish May 12 '21 at 14:30
0

I don't know exact content of the getMediaInfo function. But if it doesn't return a promise you can't use await before calling it.

Check this out:

const getMediaInfo = (data) => {
    return new Promise(async (resolve, reject) => {

        try {
            let response = await axios.get(data); // data must be a url ofc
            resolve(response); // Resolve must get a data you want to get when you call getMediaInfo
        } catch (error) {
            reject(error);
        }

    });
}

const postsWithImageURLS = [];
res.data.forEach(async (post) => {
    const response = await getMediaInfo(post.featured_media);
    postsWithImageURLS.push({...post, featured_url: response});
});
console.log(postsWithImageURLS);
Murat Colyaran
  • 2,075
  • 2
  • 8
  • 27