2014-09-12 188 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