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