2017-04-13 86 views
0

我在更新節點應用程序中的全局變量時遇到問題。有人可以看我的代碼,並讓我知道發生了什麼問題嗎?我定義了一個dowhile循環來運行,只要我的HTTP響應對象沒有定義「next」。在循環內部,事情按預期運行並定義了new_json.next,但while條件返回錯誤,因爲new_json.next在那裏未定義。我有點新的Javascript,所以不知何故,我的變量範圍是關閉的,但我不知道如何正確地做的事情根據其他問題。更新Javascript中的全局變量時遇到問題

function make_pagination_request(json, create_response_data) {  


     var new_json={}; 
     do {  

      var options = { 
       host: slug + '.nationbuilder.com', //should be replaced to be site-agnostic 
       path: json.next, 
       method: "GET", 
       json: true, 
       headers: { 
        "content-type": "application/json", 
        "accept": "application/json" 
       }, 
      }  

      var req = https.get(options, req_callback);  


      function req_callback(response) { 
       response.on('data', function(chunk) { 
        str += chunk; 
       });  

       response.on('end', function(new_json) {  

        new_json=JSON.parse(str); 
        new_results = new_json.results 
        results= results.concat(new_results); 
        console.log("combinedlength: " + results.length) 
        console.log(new_json.next); 


       }); 
      } 
     } while (new_json.next.includes("api")); 

回答

1

問題是HTTPs請求是異步的,而do/while循環是同步的。在這種情況下,在將包含next的值分配給new_json變量之前,會達到while語句。

當第一次回調函數還沒有調用while語句時。因此,new_json的值是{}(初始值),它缺少next。因此,您遇到的錯誤。

但是,解決方案並沒有解決初始值爲new_json。解決方案是刪除do/while循環並繼續在HTTP請求回調中工作。

+0

我應該知道這是類似的東西。這是我纔開始理解的,也是我其他一些問題的根源。我最終只是簡單地從本身的最後調用函數make_pagination_request。 –

+1

Javascript代碼和包含在該語言中的同步構造的異步性質一直是很多程序員的一個很大的問題來源。我在你的評論中看到,你設法通過再次調用相同的函數來解決問題。即使它工作,我建議你研究一個更好的解決方案,因爲如果函數調用自己多次,你將會遇到堆棧溢出問題。 – yeiniel

+0

我以爲我已經達到堆棧溢出問題 –

0

這是我工作的代碼。謝謝yeiniel。我最終只是簡單地從本身的最後調用函數make_pagination_request。我還做了一些與原始問題無關的其他更改,但這些更改對於調試是必需的。

function make_pagination_request(json, create_response_data, callback, tokens, options) {   

      path = json.next + "&access_token=" + tokens[slug];  


      var options = { 
       host: slug + '.nationbuilder.com', //should be replaced to be site-agnostic 
       path: path, 
       method: "GET", 
       json: true, 
       headers: { 
        "content-type": "application/json", 
        "accept": "application/json" 
       }, 
      }  

      var str='';   

      var req = https.get(options, req_callback);   


      function req_callback(response, create_response_scripts) { 
       response.on('data', function(chunk) {  

        str += chunk; 
       });   

       response.on('end', function() { 

        new_json=JSON.parse(str); 
        new_results = new_json.results 
        results= results.concat(new_results); 
        console.log('combined_length: ' + results.length) 


        if (new_json.next) { 
         make_pagination_request(new_json, create_response_data,create_response_scripts, tokens, options); 
        } else { 
         create_response_data(results, query, create_response_scripts); 
        } 


       }); 
      } 
     }