Created
April 22, 2013 07:18
-
-
Save boronine/5433006 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Asynchronous coding takes a bit of time to wrap your head around. | |
// I can't know for sure, but I think you misunderstand the general | |
// nature of a callback function. 'ajax.post' doesn't wait for the | |
// request to complete before returning, if it did so, there wouldn't | |
// be any need for a callback. **If you want something to happen AFTER | |
// the request completes, you have to put it in the callback function.** | |
// Don't think of a callback as some kind of icing on the cake, it is | |
// literally the continuation of your program's logic. | |
// To see this better, it helps to use *anonymous functions*, that is, | |
// instead of assigning a function to a variable and then referencing | |
// it as a callback, put the function directly into 'ajax.post'. | |
function meal() { | |
ajax.post("http://example.com/get_soup", function(soup) { | |
eat(soup); | |
ajax.post("http://example.com/get_steak", function(steak) { | |
eat(steak); | |
ajax.post("http://example.com/get_cake", function(cake) { | |
eat(cake); | |
}); | |
}); | |
}); | |
} | |
// Or, if you like setting variables: | |
function meal() { | |
var soup; | |
var steak; | |
var cake; | |
ajax.post("http://example.com/get_soup", function(s) { | |
soup = s; | |
ajax.post("http://example.com/get_steak", function(s) { | |
steak = s; | |
ajax.post("http://example.com/get_cake", function(c) { | |
cake = c; | |
eat(soup); | |
eat(steak); | |
eat(cake); | |
}); | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment