2015-09-06 193 views
0

我有以下代碼:異步功能將數據傳遞給異步功能

//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()工作。

我也嘗試過增加超時時間,但它不起作用。 任何建議如何克服?

+0

您需要正確傳遞迴調。見http://blog.slaks.net/2015-01-04/async-method-patterns/ – SLaks

+0

你的標籤之一是angularjs,所以我建議你看看'promise's http://stackoverflow.com/問題/ 15604196/promises-in-angularjs-and-where-use-them – Jan

回答

0

您可以修改您的LocalStoresService.getLocalStores方法以接受回調。

function getLocalStores (arg1, arg2, cb) { 
    // do stuff. 
    var localStores = 'w/e'; 
    if (typeof cb === 'function') return cb(localStores); 
} 

所以你的調用方法是這樣的:

var coords = LocationService.getLocation(); 

LocalStoresService.getLocalStores(coords[0], coords[1], function (localStores) { 
    console.log(localStores); // 'w/e' 
}); 

這真的取決於你所使用的技術類型,如「正確」的實現異步方法可以改變從類型式(angularJS,的NodeJS,香草JS等)

+2

其中一個問題的標記是angularjs,所以我認爲承諾是要走的路 – Jan

+0

我完全同意,Angular是在Ionic的核心,所以這裏沒有爭論。我給了香草JS的一個例子,因爲在我看來,他在初學者水平。 – Davion

+0

太棒了!承諾解決了我的問題:) – radioaktiv

0

據我瞭解你的項目可能會使用angularjs我給例如此基礎上,

.factory('LocationSerivice', function ($http) { 

return{ 

    getLocation : function() { 
     return $http.get('location_api'); 
    }; 

    getLocalStores : function(coords){ 
     return $http.get('your_local_store_api'); 
    }; 

    } 
}); 

現在致電您的API

LocationService.getLocation().success(function(coords){ 
     LocationService.getLocalStores(coords).success(function(localStores){ 
      console.log(localStores); 
     }); 
});