0

I have starter code from an API that allows me to search for a term, like Apple, and prints a list of JSON objects to the console.

var params = {
  q: "Apple",
  tbm: "isch",
  ijn: "0"
};
                  
var callback = function(data) {
  console.log(data["images_results"]);
};
                
src.json(params, callback);

I want to save the data["images_results"] term to a variable instead of printing to console. So far I have tried setting a var to data["images_results"] in the callback function (var was initialized outside of the function however), and in another case I set it equal to src.json(params, callback) after. But when I try to access the variable, it shows as undefined. How can I access data["images_results"] with this API instead of printing the results to console?

var a;

var params = {
  q: "Apple",
  tbm: "isch",
  ijn: "0"
};
                  
var callback = function(data) {
  a = data["images_results"];
};
                
src.json(params, callback);

console.log(a);

Updated


const params = {
            engine: "google",
            google_domain: "google.com",
            hl: "en",
            gl: "us",
            device: "desktop",
            tbm: "isch",
        };

        const getJson = async () => {
            return new Promise((resolve) => {
              src.json(params, resolve);
            });
        };

        const getFirstImages = async () => {
            const imres = [];
            for (item in items) {
              params.q = item['sku'];
              const json = await getJson();
              imres.push(json.images_results[0]["original"]);
            }
            return imres;
          };

          getFirstImages().then(imres => {
            console.log(imres);
            images = imres;
            myCache.set('total_images', images);
        })

6
  • This code is puzzling because it's sending an object (not a json string) to a function called json. The json function that's part of the fetch api parses a json request or response and returns a promise, which is really at the heart of your question, I think. Commented Jul 31, 2022 at 19:21
  • Can you provide full code that generate undefined var? Commented Jul 31, 2022 at 20:10
  • I'm sure what's happening is the OP is hoping to access callback data param outside of the scope of the callback, before the callback has been invoked, but it's hard to say much more useful without a more complete question. Commented Jul 31, 2022 at 22:19
  • @danh I have edited the post and included the code I was trying to use to store the data. Here is a link for the API if it helps serpapi.com/images-results. Commented Aug 1, 2022 at 1:04
  • @Alaindeseine I have edited the post so it shows how I tried to store the results. I have also linked the API in the above comment Commented Aug 1, 2022 at 1:05

1 Answer 1

1

You can't save result from SerpApi in that way, because .json method is asynchronous and the callback function runs after you print a in console. You need to work with results only in some function, because you can't use something like await in the global scope. If you tell me more what you want to do next with these results, I can help you better. But now you can do something like this:

var params = {
  q: "Apple",
  tbm: "isch",
  ijn: "0"
};
                  
var callback = function(data) {
  var a = data["images_results"];
  
  // do what you want to do next in this function
};
                
src.json(params, callback);

Or you can use .then chaining:

const params = {
  q: "Apple",
  tbm: "isch",
  ijn: "0"
};

const getJson = () => {
  return new Promise((resolve) => {
    src.json(params, resolve);
  });
};

getJson().then(({images_results}) => {
  var a = images_results
  // do what you want to do next in this function
});

Updated:

If I understand right, you need to do something like (check in the online IDE):

const SerpApi = require("google-search-results-nodejs");
const src = new SerpApi.GoogleSearch(process.env.API_KEY); //your api key from serpapi.com

const params = {
  engine: "google",
  google_domain: "google.com",
  hl: "en",
  gl: "us",
  device: "desktop",
  tbm: "isch",
};

const searchQueries = ["apple", "cherry", "banana"];

const getJson = async () => {
  return new Promise((resolve) => {
    src.json(params, resolve);
  });
};

const getFirstImages = async () => {
  const images = [];
  for (query in searchQueries) {
    params.q = query;
    const json = await getJson();
    images.push(json.images_results[0]);
  }
  return images;
};

getFirstImages().then(images => {
    console.log(images)
    // or do what you want to do next
})

Please note that we fill the array with images in the asynchronous function getFirstImages, waiting (await) to receive an object with results (json). And another note, you can't use array methods (e.g. forEach) to iterate over searchQueries, because await won't work.

Output:

[
   {
      "position":1,
      "thumbnail":"https://serpapi.com/searches/62e7affb9bddf73501bfde87/images/d6db51527c0e83ba92158999bf4cd1063f03d4fcbdfbcca0bb5f77b191b27a53.png",
      "source":"en.wiktionary.org",
      "title":"0 - Wiktionary",
      "link":"https://en.wiktionary.org/wiki/0",
      "original":"https://upload.wikimedia.org/wikipedia/commons/thumb/6/6e/Z%C3%A9ro.svg/1200px-Z%C3%A9ro.svg.png",
      "is_product":false
   },
   {
      "position":1,
      "thumbnail":"https://serpapi.com/searches/62e7affed737d7249d50f729/images/920c4e458460303dc0bb77ec3f448f9ad3946e5412eb72ca3cbb8751a8cee7c6.png",
      "source":"en.wiktionary.org",
      "title":"1 - Wiktionary",
      "link":"https://en.wiktionary.org/wiki/1",
      "original":"https://upload.wikimedia.org/wikipedia/commons/thumb/0/08/Un1.svg/1200px-Un1.svg.png",
      "is_product":false
   },
   {
      "position":1,
      "thumbnail":"https://serpapi.com/searches/62e7b0064055aa23fb85ce10/images/4036a5ed1a2cf55b31ca73fd5c660dc71431f02052cf7ee6f4796043060b475c.png",
      "source":"en.wiktionary.org",
      "title":"2 - Wiktionary",
      "link":"https://en.wiktionary.org/wiki/2",
      "original":"https://upload.wikimedia.org/wikipedia/commons/thumb/3/3b/Deux.svg/1200px-Deux.svg.png",
      "is_product":false
   }
]
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks! All of the code is currently in a loop and there is some code after what I shared before the loop repeats. Should I put all of the remaining code in the then function, or just the code which involves var a? I would like to save the first element of a and append it to a list. I am currently looping through a list of queries and would like to get the first image result for each, and save all of these results to a list.
I updated my answer, please check it.
I am getting this error: { "error": "Missing query q parameter." }. I have updated the original question to show the current state of my code.
Never mind. When I changed the for in loop to a regular for loop with index i, the problem was resolved. Thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.