2017-03-04 30 views
0

在下面的代碼中,有些情況下我可能會發現自己位於錯誤的頁面上,然後在滿足特定條件時重新路由。在這種情況下,我將如何從代碼中調用$ http.get調用,並在繼續執行腳本之前等待html源代碼被恢復?在繼續執行腳本之前從新網址檢索html

function checkUrl(url, size, code) { 
    return $http.get(url).then(function(response) { 
     var html = response.data; 

     var listedPage = utility.countClass(html, 'product-tile'); 

     if(listedPage > 1) { 
       url = getCorrectPage(html, code); 

       // this doesn't work, but I want to acquire the html of the newly acquired url 
       $http.get(url).then(function(response) { 
        html = response.data; 
       }); 
     } 

     stockData.name = getProductName(html); 

     return stockData; 
    }); 
} 
+0

當你說「這行不通」,在*什麼方式*它「不工作」?它如何失敗? 「url」不是你期望的那樣嗎?答案不是你期望的那樣嗎?還有別的嗎? – David

回答

1

怎麼是這樣的:

function checkUrl(url, size, code) { 
    return $http.get(url).then(function(response) { 
     var html = response.data; 
     var listedPage = utility.countClass(html, 'product-tile'); 

     if(listedPage > 1) { 
      url = getCorrectPage(html, code); 
      return $http.get(url).then(function(response) { 
       html = response.data; 
       stockData.name = getProductName(html); 
       return stockData; 
      }); 
     } 
     else { 
      stockData.name = getProductName(html); 
      return stockData; 
     }    
    }); 
} 
0

您無法在JavaScript中編寫同步I/O。最接近你想要的是Promise

0

問題是,您正在創建一個不可能的邏輯,因爲$http.get(url)的異步性質。

異步就像你告訴js:聽這個,當它完成時調用這個函數,我傳遞給你。 因此,你給他這個指令,並將它委託給另一個線程,並且繼續立即運行你的程序。 當該線程返回時,它將運行您傳遞給它的函數。但是這總是在你的其他代碼已經完成執行之後。

因此,無法按照您的代碼結構化的方式進行操作。

您必須重新配置,以便將所需的操作包含在您傳遞給$http.get(url)的功能中。

相關問題