2014-09-12 147 views
0

我在遇到以下代碼片段時遇到了問題。我的init方法需要運行並在initializeMapp()和geoListen()可以運行之前完成getLocation()函數。我將rsvp.js鏈接爲資源,但不太確定如何實現。我也嘗試了jQuery $ when.done方法。任何幫助表示讚賞。試着讓Javascript函數同步運行

jQuery的方法:

//initial page load method 
function init() { 

    //get user location then builds map and listens to database 
    $.when(getLocation()).done.(function() { 

     //build map now that you have user location 
     initializeMap(); 

     //Starts listening to database changes 
     geoListen(); 

    }) 

} 

RSVP方法:

//initial page load method 
function init() { 

     //get user location then builds map and listens to database 
    getLocation().then(function() { 

    //build map now that you have user location 
    initializeMap(); 

    //Starts listening to database changes 
    geoListen(); 

    }) 

} 
+1

究竟發生什麼,當你運行這些代碼片段一個承諾? getLocation()返回什麼? – ajp15243 2014-09-12 20:53:00

+0

getLocation是否返回承諾? – Magrangs 2014-09-12 20:56:35

回答

0

,你可以讓你的getLocation函數接受回調並執行他們的時候getLocation完成

getLocation = function(cb1, cb2) { 
    // when done 
    cb1() 
    cb2() 
} 

function init() { 
    getLocation(initializeMap, geoListen) 
} 

,或者你可以傳遞一個回調引用數組並通過它們循環i ñgetLocation,並呼籲他們

或者您可以使用Q.js和報酬getLocation

+0

如果getLocation返回承諾,則不需要執行此操作。 – Magrangs 2014-09-15 10:48:19