Javascript, Async and Callbacks

So most of my programming experience has been using either Python to write scripts or Java for writing applications. Because of this I expected all code to execute one line after the other (as I had never encounted asychronous functions before).

As a result of this, I would write code that looked like this:

Bad Function

And then call it with something like:

Bad Call

And then it would immediately log undefined and I would be very confused. The reason for this of course, is that Javascript is asychronous - scanNetwork takes time to run, so Javascript goes ahead and runs the console.log(result) before scanNetwork returns anything, hence the logged undefined value.

There is an obvious solution, I can go into the scanNetwork function and make it do something instead of returning the data - however this is a pretty terrible solution as it means scanNetwork is no longer a versatile function, if I want to do different things with the returned data I would need multiple scanNetwork functions.

The correct way to deal with this to use a "callback" function, which seems to be a technique that is quite heavily entrenched in the javascript world.

Bad Function

We add a third parameter, which we intend to be a function and we pass the data to the callback function. Calling scanNetwork will then look like this:

Bad Function

We can see that we are passing an anonymous function to scanNetwork, and that the data that is passed to the callback is passed back to this anonymous funtion and then console.logged.

While this does look a little confusing at first, I do feel like this is a fairly elegant way of doing things. There is the danger though of "callback hell" where each succesive function chains to another callback but that is a topic for another blog post...

Chris Tan

Random Ramblings