Javascript 使用promise在循环中填充数组

Javascript 使用promise在循环中填充数组,javascript,promise,Javascript,Promise,我开发了一个代码来获取循环语句中对象的图像信息。但是,当我在循环底部打印输出时,它是空的。有人能帮我吗?getMediaInfo函数是一个Axios调用 const postsWithImageURLS = []; res.data.forEach(async (post) => { const response = await getMediaInfo(post.featured_media); postsWithImageURLS.pus

我开发了一个代码来获取循环语句中对象的图像信息。但是,当我在循环底部打印输出时,它是空的。有人能帮我吗?getMediaInfo函数是一个Axios调用

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


您应该在所有异步方法完成后访问postsWithImageURLS。

我不知道
getMediaInfo
函数的确切内容。但是如果它没有返回一个承诺,你就不能在调用它之前使用
等待

看看这个:

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

我不知道
getMediaInfo
函数的确切内容。但是如果它没有返回一个承诺,你就不能在调用它之前使用
等待

看看这个:

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

您的数组
postswithimagerurls
被声明为空数组。您没有将任何数据推入其中。我已经修复了代码,即使将其推入数组中,循环后值也不会改变。我建议您先通读这段代码。这回答了你的问题吗?您的数组
postswithimagerurls
被声明为空数组。您没有将任何数据推入其中。我已经修复了代码,即使将其推入数组中,循环后值也不会改变。我建议您先通读这段代码。这回答了你的问题吗?您建议使用
map
而不是
forEach
。由于我实现了
if
语句,这导致了许多空条目。您对如何解决这个问题有什么建议吗?您可以使用数组的
filter
方法从数组
postswithimagers
中排除null或未定义的元素,例如:
then(postswithimagers=>postswithimagers.filter(v=>!!v))。然后(console.log)
您建议使用
map
而不是
forEach
。由于我实现了
if
语句,这导致了许多空条目。您对如何解决这个问题有什么建议吗?您可以使用数组的
filter
方法从数组
postswithimagers
中排除null或未定义的元素,例如:
then(postswithimagers=>postswithimagers.filter(v=>!!v))。然后(console.log)