Answer the question
In order to leave comments, you need to log in
`
How to return a value in async/await with forEach?
var GetImages = async() => {
var images_array = [];
await request ({
url: `https://api.tumblr.com/v2/blog/nameblog/posts?api_key=${process.env.TUMBLR_KEY}&type=photo`,
json: true
}, (error, response, body) => {
if(error){
console.log('Unable to connect');
}else if(body.meta.status === 200){
body.response.posts.forEach(function(obj) {
obj.photos.forEach(function(photo) {
if(photo.original_size.width>photo.original_size.height){
images_array.push(photo.original_size.url);
console.log("dawdaw");
}
});
});
//callback(images_array);
}
});
return mages_array;
}
Answer the question
In order to leave comments, you need to log in
forEach has absolutely nothing to do with it.
Stop treating await as some magical thing that will do everything for you.
If you don't understand how it works - rewrite the code to promises. By the way, await won't help here at all.
const getImages = async () =>
new Promise((resolve, reject) =>
request({
url: `https://api.tumblr.com/v2/blog/nameblog/posts?api_key=${process.env.TUMBLR_KEY}&type=photo`,
json: true,
},
(error, response, body) => {
if (error) {
reject('Unable to connect');
} else if (body.meta.status === 200) {
body.response.posts.forEach((obj) => {
const photos = obj.photos
.filter(photo =>
photo.original_size.width > photo.original_size.height,
).map(photo => photo.original_size.url);
resolve(photos);
});
}
}),
);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question