0

I'am passing an array with images titles and I need google to search each title and return me it's image link. When google returns a link I push it to an empty array to get all the links for my images. I don't know how could I return the array with links, because as it is now the script olny returns an empty array, it probably because the program executes return before the array is filled? So in summary I need to return array from this function. By the way if I console.log(as) in every iterration of foreach I get the array with links, so google API returns the link.

const google = require('googleapis').google
const customSearch = google.customsearch('v1')
async function paieska (placestitles) {
let as = [];
const error = "Image not found";
placestitles.forEach(async title => {
  const response = await customSearch.cse.list({
  auth: 'MY_API_KEY',
  cx: 'MY_CX',
  q: title,
  num: 1,
  searchType: 'image',
  imgSize: 'medium'
})
  if(response.data.items) {
    response.data.items.map((item) => {
    as.push(item.link);
    });
  }
  else {
    as.push(error);
  }
});

return as;

}

Ausrys
  • 9
  • 4
  • 1
    Does this answer your question? [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – evolutionxbox May 25 '21 at 09:45
  • I didn't find the answer to my question there. – Ausrys May 25 '21 at 09:59
  • You can't use `async/await` inside `.forEach()` or any other array method (`.map()`, `.filter()` etc), but you can inside a `for(...)` loop. Use `for( let title of placestitles){ ... ` – Jeremy Thille May 25 '21 at 10:06
  • @JeremyThille why not? https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop – evolutionxbox May 25 '21 at 10:07
  • Also, your use of `.map()` is wrong. `.map()` is used to transform every item in an array, and as such must return a value. It should be `as = response.data.items.map( item => item.link)`. – Jeremy Thille May 25 '21 at 10:09
  • @evolutionxbox Interesting, let me try something – Jeremy Thille May 25 '21 at 10:10
  • @evolutionxbox Looks like I'm right? https://codepen.io/jeremythille/pen/ExWXjKa?editors=0010 – Jeremy Thille May 25 '21 at 10:17
  • @JeremyThille yeah that makes sense. At that point I'd use `await Promise.all(outputMap)` to get all the results. – evolutionxbox May 25 '21 at 10:20
  • @JeremyThille thank you for your advices, I edited the code as you suggested and it worked. Also my solution was `as.push(response.data.items.map( item => item.link))` which in the end returns an array of all images links. – Ausrys May 25 '21 at 10:52

0 Answers0