我有以下代碼:異步功能將數據傳遞給異步功能
//calling AsyncFunction
var coords = LocationSerivice.getLocation();
var localStores;
setTimeout(function(){
//works
console.log(coords);
//calling async function again
localStores = LocalStoresService.getLocalStores(coords[0],coords[1]);
}, 100);
setTimeout(function(){
//doesn't work
console.log(localStores);
}, 100);
什麼是我想要做的是首先調用一個異步函數,返回我的位置。然後爲了從該功能獲取數據,我正在設置超時。隨着收到的數據,我打電話給第二個異步功能。我再次設置超時爲了從我的第二個異步函數獲取數據,所以在這裏失敗。如果我嘗試在超時塊中顯示console.log()
的數據,則表示undefined
,而第一個超時塊中的console.log()
工作。
我也嘗試過增加超時時間,但它不起作用。 任何建議如何克服?
您需要正確傳遞迴調。見http://blog.slaks.net/2015-01-04/async-method-patterns/ – SLaks
你的標籤之一是angularjs,所以我建議你看看'promise's http://stackoverflow.com/問題/ 15604196/promises-in-angularjs-and-where-use-them – Jan