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.
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.
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 :)