我正在尝试使用Bing Search Image API搜索一个我称之为names
的项目数组。我已经使用了文档https://learn.microsoft.com/en-us/azure/cognitive-services/bing-image-search/quickstarts/nodejs来开始发送JSON解析请求。当单独调用名称时,我能够收到图像URL,但是当我通过for
循环运行bing_image_search
函数时,控制台会打印出找不到图像结果的信息,如果它确实找到其中一些图像,则这些图像未按照bing_image_search
函数调用每个名称的顺序返回。以下是目前我所做的代码,感谢任何帮助。
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]);
}