使用 Bing 图片 API Javascript 搜索图片

Search for Images using Bing Image API Javascript

我正在尝试使用 Bing 搜索图像 API 来搜索我称为 names 的项目数组。我已经使用 https://docs.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]);
  }

您可能需要考虑将 bing_image_search 逻辑包装在一个 promise 中,以便更轻松地控制流程...看看下面的内容是否对您有帮助:

const { RateLimiter } = require("limiter");
const limiter = new RateLimiter({ tokensPerInterval: 3, interval: "second" });

var imagesArr = [];
let num_results = 1;
var names = []; // assume already filled with names

function bing_image_search(search) {
    return new Promise(async (resolve,reject)=>{
        const remainingMessages = await limiter.removeTokens(1);
        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)=>{
            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);
                    resolve(imageLink);
                }
                else {
                    resolve("Couldn't find image results!");
                }
            });
            response.on('error', function (e) {
                reject(e);
            });       
        });
      
        req.on('error', (e) => {
            reject(e);
        });
      
        req.end();
    })
}

(async()=>{
    let imgUrls = []
    for (const name of names){
        let imgurl = await bing_image_search(name)
        imgUrls.push(imgurl)
    }   
})()