Try to get Javascript functions to run Synchronously

68 Views Asked by At

I'm having trouble with the following code snippet. My init method needs to run and complete the getLocation() function before the initializeMapp() and geoListen() can run. I have rsvp.js linked as a resource, but not quite sure how to implement. I also tried the jQuery $when.done method. Any help is appreciated.

jQuery Method:

//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 method:

 //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

There are 1 best solutions below

1
On

you can make your getLocation function accept callbacks and execute them when getLocation finishes

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

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

or you can pass an array of callback references and loop through them in getLocation and call them

alternatively you can use Q.js and return a promise from getLocation