2

can someone please help me to get my head around this code ? I can't quite determine by myself what code will be executed first in this case :/ Apparently this ensures that it will always print 1 to the console, but i don't get why is that. Also the line with "orig_fn.bind.apply..." is quite confusing for me :/

function asyncify(fn) {
 var orig_fn = fn,
 intv = setTimeout( function(){
 intv = null;
 if (fn) fn();
 }, 0 )
 ;
 fn = null;
 return function() {
 // firing too quickly, before `intv` timer has fired to
 // indicate async turn has passed?
 if (intv) {
 fn = orig_fn.bind.apply(
 orig_fn,
 // add the wrapper's `this` to the `bind(..)`
 // call parameters, as well as currying any
 // passed in parameters
 [this].concat( [].slice.call( arguments ) )
 );
 }
 // already async
 else {
 // invoke original function
 orig_fn.apply( this, arguments );
 }
 };
}
function result(data) {
 console.log( a );
}
var a = 0;
ajax( "..pre-cached-url..", asyncify( result ) );
a++;
asked Sep 23, 2016 at 16:57
3
  • I would start by reading the documentation on bind, apply, setTimeout, etc. Commented Sep 23, 2016 at 17:08
  • Also, just get a debugger on it and step through the code. That's the easiest way of seeing "what code will be executed first". Commented Sep 23, 2016 at 17:09
  • debugger will probably fail miserably at trying to investigate async calls. It can be done, but requires certain mastery at using chrome dev tools. Commented Sep 23, 2016 at 17:15

1 Answer 1

1

Let's understand what your asyncify() function does.

First, notice that it gets called immediately, to provide its result as a second argument of your ajax() call. It returns an anonymous function.

Now, depending on when that anonymous function is called, one of two things happen:

1) if it's called immediately, the setTimeout didn't trigger yet, therefore it gets the arguments it was called with, and wraps them together with the original function asyncify() was called with, which is result in your case. The wrapping is done using bind(). Then it exits, letting timeout handle the actual call.

2) if it's not called immediately, when it is called, the timeout has lapsed already, so it can call the original function with its new parameters right away. This is done using apply().

answered Sep 23, 2016 at 17:13
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.