2017-02-11 195 views
0

我在調用web服務的控制器中使用$ http get來檢索一些數據。這是下面的代碼:JavaScript - 減速循環

UPDATE碼

var boolGetBoothCoords = false; 
     BoothDesignatedCoordsService.getBoothDesignatedCoords(strListShortListedBooth[i], 3) 

.then(function(response) { 
     var data = response.data 
     console.log('data', data.arrBoothDesignatedCoords) 
     boothDesignatedCoords = data.arrBoothDesignatedCoords; 
     boolGetBoothCoords = true; 
}) 

console.log("boothDesignatedCoords ", boothDesignatedCoords); // undefined 
// And a lot of other codes 

然而,由於$ HTTP GET是異步方法,程序將立即boothDesignatedCoords是未定義後調用控制檯日誌和代碼。我不要那個。我希望程序在Web服務使用完成後調用控制檯日誌和代碼。所以我做了以下使用這樣的回答:how to slow down a javascript loop

go(); 
    function go() { 
     console.log("hello"); 

     if (boolGetBoothCoords == false) { 
      setTimeout(go, 1000); 

     } 
     else 
     { 

     } 
    } 
    go() 

    console.log("boothDesignatedCoords ", boothDesignatedCoords); // undefined 
    // OTHER CODES that uses variable boothDesignatedCoords will be undefined  as well 

不過,我不知道爲什麼它仍然會調用控制檯日誌,但Web服務消費還沒有完成,儘管使用這種方法。有人可以幫幫我嗎?謝謝。

+0

爲什麼不在'fnProceedOtherTask1()'調用的最後'then'回調中包含'console.log'? – andrusieczko

+0

對不起,感到困惑。我仍然更新了我的問題 – Antoni

+0

,最好在最後一次回調中打印它比等待使用'setTimeout'更好...如果服務器響應時間超過1秒會發生什麼?它仍然是undefined – andrusieczko

回答

1

setTimeout是異步的,所以實際上你真的沒有區別,調用go函數。

會發生什麼事是:

  • 通話go()功能
  • 通話setTimeout裏面的功能 - 這將安排go在(大約)1S
  • 電話console.log
之後立即調用

你可能想要的是把你的console.log撥打then致電回到這樣的:

var boolGetBoothCoords = false; 
 
BoothDesignatedCoordsService.getBoothDesignatedCoords(strListShortListedBooth[i], 3) 
 
    .then(function(response) { 
 
    return response.data.arrBoothDesignatedCoords; 
 
    }) 
 
    .then(function(boothDesignatedCoords) { 
 
    console.log("boothDesignatedCoords ", boothDesignatedCoords); 
 
    });


其他選項(不推薦)將是把console.logif聲明else部分在go功能。

在這種情況下,您應該在整個代碼片段之前定義boothDesignatedCoords

+0

嗨,但如果我按照你的代碼還有另一個問題。之前。然後(函數(boothDesignatedCoords)方法被調用,程序已經退出控制器 – Antoni

+0

我想你正在使用AngularJS,你想改變'$ scope'...那麼我建議你應該在回調中對其進行所有更改 – andrusieczko

1

假設在響應後運行的代碼應在響應之後調用。

var boolGetBoothCoords = false; 

BoothDesignatedCoordsService.getBoothDesignatedCoords(
    strListShortListedBooth[i], 3) 

.then(function(response) { 
    var data = response.data 
    console.log('data', data.arrBoothDesignatedCoords) 
    boothDesignatedCoords = data.arrBoothDesignatedCoords; 
    boolGetBoothCoords = true; 
    codeThatUsesTheResponseData(); 
}); 
function codeThatUsesTheResponseData() { 
    console.log("boothDesignatedCoords ", boothDesignatedCoords); // undefined 
    // And a lot of other codes 
} 
+0

嗨,但如果我遵循你的代碼,還有另一個問題。在調用CodeThatUsesTheResponseData方法之前,程序已經退出控制器 – Antoni

+0

它會在哪個行後退出?在某些時候應該有一個返回,異常或刷新,以使代碼不會調用下一行。 –