简体   繁体   English

使用 promise 在循环中填充数组

[英]Populate an array in the loop using promise

I have developed a code to fetch the image information of an object inside a loop statement.我开发了一个代码来在循环语句中获取 object 的图像信息。 However, when I print the output at the bottom of the loop, it is empty.但是,当我在循环底部打印 output 时,它是空的。 Can anyone help me with this, please?有人可以帮我解决这个问题吗? The getMediaInfo function is an Axios call. getMediaInfo function 是一个 Axios 调用。

    const postsWithImageURLS = [];
    res.data.forEach(async (post) => {
        const response = await getMediaInfo(post.featured_media);
        postsWithImageURLS.push({...post, featured_url: response});
    });
    console.log(postsWithImageURLS);
 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.您应该在所有异步方法完成后访问postsWithImageURLS

I don't know exact content of the getMediaInfo function.我不知道getMediaInfo function 的确切内容。 But if it doesn't return a promise you can't use await before calling it.但如果它不返回 promise ,则在调用它之前不能使用await

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM