有没有办法,原始JavaScript或通过插件,将检测给定的函数是否内部有一个AJAX调用?我最近一直在使用API,而且我的一些代码经常出现“早一点”而不是因为前一个脚本包含异步AJAX调用。例如:
<base href="/">
<!-- Set the base href -->
<script>document.write('<base href="'+ document.location +'"/>');</script>
我知道如何在JQuery上做AJAX承诺,虽然我可能需要永远重新编写那些外部JS文件中的AJAX调用。另外配置那些外部JS文件会很危险,我甚至不知道是否有其他页面使用那些可能会受到影响的JS。删除“重新编码”作为解决方案,我正在寻找另一种功能来检查是否:
目前,我正在使用一种利用类似于var doSomething = function(by, activity) {
// Call something from the API of from another developer
// or a function() from a 3rd party JS library.
var anonFunction = API.package[by][activity]; // or anonFunction = 3rpPartyJS();
if(anonFunction === undefined) {
return "skipped";
}
else {
var response = anonFunction();
// The problem is that the code below will execute not knowing whether
// there are still AJAX call/s pending within the var anonFunction
// initialization. If there is indeed an AJAX call (which sometimes there
// aren't, depends on the <function name> called above), the script below
// will be executed a little bit earlier than it should be.
if(response["success"] === true) {
... // do something
return "done";
}
else {
alert("Failed to call function " + by + "." + me);
return "fail";
}
}
}
$(function() {
// This is successful.
doSomething("me", "aSyncFunction");
// This returns "fail", even thought the response returns
// successful (after some X milliseconds later).
doSomething("me", "anAsyncFunction");
});
功能的笨拙解决方案,但我知道这不是一个好的解决方案。我需要这样的东西:
sleep()