happilyUnStuck
happilyUnStuck

Reputation: 372

Coffeescript running a second function before the first has finished executing

My code is as follows. I would expect the code inside configureMission() to finish running before running mapSurface. This does not appear to be happening.

missionCommands = "" # you don't have a mission yet
$('#startExploration').click -> # Set #missionControl as input for game configuration
    configureMission()
    mapSurface()        

configureMission =-> 
   $('#MissionControl').on "submit", ->
      # cool helper function shamelessly pinched from http://jsfiddle.net/sxGtM/3/
      $.fn.serializeObject = function() # not shown

      missionCommands = JSON.stringify($('form').serializeObject())
      return false #stops click event from firing

 mapSurface =->
    console.log('map')
    console.log(missionCommands)

I have noticed that if I submit the form a second time, the missionCommands variable has been updated with the json data, so it appears that the form data has been processed, but that this is happening after the second function has run.

map login.js:60
   login.js:61
map login.js:60
{"xMaximum":"","yMaximum":"","xCoord":["iuoiuyi",""],"yCoord":["",""],"orientaiton":["",""]} login.js:61

I can make it work by moving the mapSurface function inside the configureMission function, but this seems like bad form. I wonder, is there a more correct pattern I could use to achieve my desired result of processing the form data into json, setting this into a variable and passing the variable to a second function.

Upvotes: 2

Views: 297

Answers (1)

Graham Swan
Graham Swan

Reputation: 4828

You're treating asynchronous commands as synchronous commands. JavaScript (and thereby CoffeeScript) works asynchronously, meaning that functions will be run in parallel.

You can solve this problem by specifying mapSurface() as the callback for configureMission() as follows:

missionCommands = ""
$('#startExploration').click ->
    configureMission(mapSurface)

configureMission = (cb) -> 
   console.log "now running configureMission()"
   $('#MissionControl').on "submit", ->
      $.fn.serializeObject = function() # not shown

      missionCommands = JSON.stringify($('form').serializeObject())
      console.log "completed configureMission()"
      return cb()

mapSurface = ->
   console.log "now running mapSurface()"
   console.log missionCommands
   console.log "completed mapSurface()"

Learn about JavaScript callbacks here: http://recurial.com/programming/understanding-callback-functions-in-javascript/.

Upvotes: 1

Related Questions