Now to explain the signifigance of thunks.
function frokneeAjax ( url , cb ) {
var sampleResponses = {
" file1 " : " Yo mama got the wooden leg with real feet " ,
" file2 " : " Yo mama's glasses so thick, when she looks at maps she can see people waving at her " ,
" file3 " : " Yo mama's an extra on the Simpsons "
}
var randomDelay = Math . floor (( Math . random () * 10000 ));
console . log ( " Making Ajax request... " );
setTimeout ( function () {
cb ( sampleResponses [ url ]);
}, randomDelay );
};
function output ( text ) {
console . log ( text );
};
// Working backwards, assign three thunks for each of the asynchronous file requests.
// The idea is to make these requests in parallel.
var thunk1 = getFile ( " file1 " );
var thunk2 = getFile ( " file2 " );
var thunk3 = getFile ( " file3 " );
// Invoke the thunks, and pass a callback function to just output each response.
thunk1 ( function ( text1 ) {
output ( text1 );
thunk2 ( function ( text3 ) {
output ( text3 );
thunk3 ( function ( text3 ) {
output ( text3 );
});
});
});
// Implement getFile() so that it immediately makes the frokneeAjax request.
// The key is to use closure to store the state of the AJAX response and the callback function.
// Either the AJAX request resolves before the callback is invoked
// or the callback is invoked before the AJAX request resolves.
// Using closure and control flow, both cases can be addressed.
function getFile ( file ) {
var text , fn ;
frokneeAjax ( file , function ( res ) {
fn ? fn ( res ) : text = response ;
// Check to see if a callback has been passed.
// If yes, just invoke it with the AJAX response.
// If not, then save the AJAX response to a variable.
});
return function ( cb ) {
text ? cb ( text ) : fn = cb ;
// Check to see if the AJAX response has come back.
// If yes, invoke the callback and pass the AJAX response.
// If not, save the callback so that the AJAX request can make this call later.
};
};
The key takeaway from thunks is that it factors time out of the equation, making code easier to reason about. Thunks abstract time away and allows developers to focus on crucial logic. Think of how many AJAX requests or Promises you’ve ever written. Have you thought about what’s going on behind the scenes? That said, Thunks have a weird name, and can be seen as a predecessor to Promises in JavaScript.