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);
4
  • Your array postsWithImageURLS is declared as an empty array. You're not pushing any data into it. Commented May 12, 2021 at 13:15
  • I have fixed the code, even by pushing it into the array the value does not change after the loop Commented May 12, 2021 at 13:17
  • I suggest you read through this first. stackoverflow.com/questions/14220321/… Commented May 12, 2021 at 13:18
  • Does this answer your question? Using async/await with a forEach loop Commented May 12, 2021 at 13:19

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
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)
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.