Skip to content

Instantly share code, notes, and snippets.

@ultim8k
Last active June 17, 2018 22:19
Show Gist options
  • Save ultim8k/5813245 to your computer and use it in GitHub Desktop.
Save ultim8k/5813245 to your computer and use it in GitHub Desktop.
Asynchronous functions in Javascript

Asynchronous functions in Javascript

The problem

Some times we want to get data from a function that isn't ready on time, and it's response is delayed. Those functions are called Asynchronous.

var profile = $.get('http://graph.facebook.com/kapenekos',
	function(response){
		console.log(response)
		return response
	})
	
console.log(profile) // undefined

While console.log(response) shows the result, profile is undefined when we try to get it, because the Ajax Request has not finished yet, so the return response has not run.

The solution

a) Using Callbacks

In order to pass the data we can use a 'callback' function:

function dataParsing(data){
	console.log('Hi,\nMy name is ' + data.first_name + '.')
}

$.get('http://graph.facebook.com/kapenekos',
	function(response){
		console.log(response)
		dataParsing(response)
	})

or

function dataParsing(data){
	console.log('Hi,\nMy name is ' + data.first_name + '.')
}

$.get('http://graph.facebook.com/kapenekos', dataParsing)

What we actually do is pass the result-handling function as a parameter to the asynchronus function. When our data is ready, the asychronous function will run the callback for us.

b) Using Promises

Using Callbacks is easy and solves our problem. But soon we'll end up with a code like this:


// Warning Pyramid indented code ahead
$.get('http://graph.facebook.com/kapenekos',
	function(response){
		console.log(response)
		function(response){
			var parsed = response
			function(parsed){
				console.log(parsed)
			}
		}
	})
...

Now that sucks! A better solution is the use of promises.

function parseData(data){
	console.log('Hi,\nMy name is ' + data.first_name + '.')
}

$.get('http://graph.facebook.com/kapenekos')
.done(parseData)

With this we have decoupled the data manipulation from the asynchronus function.

Developer's soul may rest now :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment