2
有人可以幫我讓我的頭繞過這段代碼嗎?在這種情況下,我無法自己決定首先執行哪些代碼:/顯然這確保它總是將1打印到控制檯,但我不明白爲什麼。也符合「orig_fn.bind.apply ......」對我來說是相當混亂:/使功能始終是異步的
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++;
我首先閱讀[bind](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind),[apply](https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply),[setTimeout](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout)等。 –
此外,只需調試器,並通過代碼。這是查看「哪些代碼將首先執行」的最簡單方法。 –
調試器在嘗試調查異步調用時可能會失敗。它可以完成,但需要一定的掌握在使用鉻開發工具。 –