使用 promise 在循环中填充数组
Populate an array in the loop using promise
我开发了一个代码来在循环语句中获取对象的图像信息。但是,当我在循环底部打印输出时,它是空的。有人可以帮我吗? 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);
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));
您应该在所有异步方法完成后访问 postsWithImageURLS。
我不知道 getMediaInfo
函数的确切内容。但是,如果它没有 return 承诺,您就不能在调用它之前使用 await
。
看看这个:
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 函数是一个 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));
您应该在所有异步方法完成后访问 postsWithImageURLS。
我不知道 getMediaInfo
函数的确切内容。但是,如果它没有 return 承诺,您就不能在调用它之前使用 await
。
看看这个:
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);