`How to return a value in async/await with forEach?
A
A
AlexMark2017-08-12 22:54:59
JavaScript
AlexMark, 2017-08-12 22:54:59

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

I'm trying to get an array of images. But the function first makes a return, and only then forms an array of pictures. As I have not perverted, I don’t understand how to make it return after the array is formed.
Through callbak I can get this array, but I'm interested in the correct option through await / async. Thank you for your help.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nicholas, 2017-08-12
@AlexMark

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

Rewrote the nightmare that was.
Install a linter (eslint), read about the filter, map methods, do not mix arrow and regular functions.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question