0

http.get リクエストでループしようとしていますが、関数が開始されない理由がわかりません。私のコードは:

while(List.length>0) {                
   if(counter < Limit) { // Limit is the amount of requests I want to 
        counter++;
        inProcess++;
        var scanitem =  List.pop();

      var body = "";    
      var url = 'https://www.mywebsite.com/'+scanitem;
      var options = {
                      path: url,                                                
                      method: 'GET'
                    };
      console.log(url); // This part is happenning
      var _request =  https.get(options, function (res) {
                       console.log('get web site');// this part is NOT showup. 
                       res.on('data', function (chunk) {
                          console.log(chunk); // this part is NOT showup. 
                          body += chunk.toString();            
                      });
                      res.on("end", function() {                            
                        console.log(body);// this part is NOT showup. 
                      });
                      res.on("error", function(error) {                         
                       console.log('error')// this part is NOT showup. 
                      });
                  });
       _request.end();         
   }                                        
   else {
      console.log('list BREAK');} // This part is happenning after the limit crossed
4

1 に答える 1

0
  1. 第 1 引数としてan を渡す場合Object、URL は個々の部分に分割する必要があります。

    var options = {
        method: 'GET',
        protocol: 'https:',
        hostname: 'www.mywebsite.com',
        path: '/' + scanitem
    };
    
    var _request = https.get(options, ...);
    

    options使用されるは、の便利なバリアントである でhttps.request()説明されています。https.get()

    URL を渡すこともできますString。これhttps.get()は実行さurl.parse()れます。

    var _request = https.get(url, ...);
    
  2. JavaScript には、ブロック スコープの変数がありません (まだ)。したがって、 の場所にもかかわらず、ループvar body = "";のすべての反復は同じ に追加されます。whilebody

    scanitemこれは、変数が、url、およびareなどの同期タスクでのみ使用される場合、それほど問題にはなりませんoptions。ただし、 のような非同期タスクを混在させると、https.get()期待した結果が得られない可能性があります。

    現在、ブロック スコープの変数がないため、クロージャを使用して追加のfunctionスコープを作成できます。

    のようListに見えArrayますが、これにはイテレータfunctionを使用できます.forEach()

    List.forEach(function (scanitem) {
        var body = '';
        var url = 'https://www.mywebsite.com/'+scanitem;
    
        https.get(url, function (res) {
            // etc.
        });
    });
    

    の場合はLimit、 を使用して必要な.splice()部分を削除して操作できArrayます。

    List.splice(0, Limit).forEach(function (scanitem) {
        // etc.
    });
    

また、 とは異なり、を使用するときhttps.request()に呼び出す必要はありません。_request.end()https.get()

于 2013-07-03T20:55:55.903 に答える