<span class="keyword">var</span> photo <span class="keyword operator">=</span> <span class="function call">downloadPhoto</span>(<span class="string">'http://coolcats.com/cat.gif'</span>) <span class="comment">// photo is 'undefined'!</span>
In this case the gif might take a very long time to download, and you don’t want your program to pause (aka ‘block’) while waiting for the download to finish.
Instead, you store the code that should run after the download is complete in a function. This is the callback! You give it to the
downloadPhoto
function and it will run your callback (e.g. ‘call you back later’) when the download is complete, and pass in the photo (or an error if something went wrong).<span class="function call">downloadPhoto</span>(<span class="string">'http://coolcats.com/cat.gif'</span>, handlePhoto) <span class="storage function">function</span> <span class="entity name function">handlePhoto </span>(error, photo) { <span class="keyword">if</span> (error) console.<span class="function call">error</span>(<span class="string">'Download error!'</span>, error) <span class="keyword">else</span> console.<span class="support method">log</span>(<span class="string">'Download finished'</span>, photo) }
Github: run-parallel (javascript)
Run an array of functions in parallel
install
npm install run-parallel
usage
parallel(tasks, [callback])
Run the
tasks
array of functions in parallel, without waiting until the previous function has completed. If any of the functions pass an error to its callback, the maincallback
is immediately called with the value of the error. Once thetasks
have completed, the results are passed to the finalcallback
as an arr
Transclusion using Github and document.write()
Github has a component that makes it easy to embed Github gists in a web page.
This is a basic form of transclusion using the <script> tag:
<script src=”https://gist.github.com/5570555.js?file=search-form-input-button.php”></script>
Fixing These jQuery! A Guide to Debugging
You cannot combine the previous two non-working techniques to create something that works
Don’t feel bad, everybody tries this once
function
getContent() {
var
stuff;
$.get(
"remote.php"
,
function
(data) {
stuff = data;
});
return
stuff;
}
var
newContent = getContent();
// newContent === undefined
This is a very bad idea. Just like $.get()
does not wait for the callback to finish, neither will the containinggetContent
function