I am trying to use the Bing Search Image API to search through an array of items that I have called names
. I have used the documentation on https://learn.microsoft.com/en-us/azure/cognitive-services/bing-image-search/quickstarts/nodejs for getting started on sending a request for JSON parsing. I am able to receive the image URLs back when calling the names individually, however, when I run the bing_image_search
function through a for
loop, the console prints that it couldn't find image results and if it does find some of them, they are not returned in order that the bing_image_search
function calls each name in. Below is the code to show what I have going now. Any help is appreciated.
var imagesArr = [];
let num_results = 1;
var names = []; // assume already filled with names
let response_handler = function (response) {
let body = '';
response.on('data', function (d) {
body += d;
});
response.on('end', function () {
let imageResults = JSON.parse(body);
if (imageResults.value) {
let imageLink = imageResults.value[0].thumbnailUrl;
//console.log(`Image result count: ${imageResults.value.length}`);
//imagesArr.push(imageLink);
//console.log(imageLink);
return imageLink;
}
else {
console.log("Couldn't find image results!");
}
});
response.on('error', function (e) {
console.log('Error: ' + e.message);
});
};
let bing_image_search = function (search) {
console.log('Searching images for: ' + search);
let request_params = {
method : 'GET',
hostname : host,
path : path + '?q=' + encodeURIComponent(search) + '&count=' + num_results,
headers : {
'Ocp-Apim-Subscription-Key' : subscriptionKey,
}
};
let req = https.request(request_params, response_handler);
req.end();
}
for(index in names) {
bing_image_search(names[index]);
}