First here is code -
From the book -
What if you don’t know whether the API in question will always execute async? You could invent a utility like this asyncify(…) proof-of-concept:
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 );
}
};
}
You use asyncify(…) like this:
function result(data) {
console.log( a );
}
var a = 0;
ajax( "..pre-cached-url..", asyncify( result ) );
a++;
Now my doubt -
ajax request will be made and the return value of asyncify(result)
will be used as callback for ajax request.
Now let’s see asyncify function-
What I see is two cases -
- callback functiion inside
intv = setTimeout ...
is put in the eventloop queue before the return function fromasyncify()
- return function from
asyncify()
is put in eventloop queue beforeintv = setTimeout ...
Let’s see case1-
callback functiion inside intv = setTimeout ...
will be executed before the return function from asyncify() in which case
// invoke original function
orig_fn.apply( this, arguments );
}```
this part will execte and I am fine with this.
***case2-***
2) return function from `asyncify()` is put in eventloop queue before `intv = setTimeout ...`
I am unable to understand in which scenario and how this is going to happen?