[英]waiting for function execution before running other code
我有一个函数可以加载JS文件,其中一个JS文件对其他代码能否成功运行很重要,因此我试图等到函数成功加载它。
到目前为止,我已经尝试了几种方法-但它们对我没有用,例如以下一种方法:
$(document).ready(function () {
function kickOff() {
return new Promise(function (resolve, reject) {
loadRemoteFile("hconfig.js");
});
}
kickoff().then(function (result) {
run the code that depends on the code that kickoff() run
});
});
LoadRemoteFile函数
function loadRemoteFile(filename, loadIntoHeader){
filetype = filename.match(".css") ? "css" : "js";
if (filetype=="js"){ //if filename is a external JavaScript file
if(!loadIntoHeader){
var script = document.createElement("script");
script.type = "text/javascript";
script.src = filename;
document.body.appendChild(script);
}else{
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", filename);
document.getElementsByTagName("head")[0].appendChild(fileref);
}
}else if (filetype=="css"){
if(!loadIntoHeader){
var style = document.createElement("link");
style.type = "text/css";
style.rel = "stylesheet";
style.href = filename;
document.body.appendChild(style);
}else{
var fileref=document.createElement("link");
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", filename);
document.getElementsByTagName("head")[0].appendChild(fileref);
}
}
}
这是一个好的解决方案吗? 为什么不起作用?
您需要在创建的Promise()
上调用resolve()
。 只有在这种情况发生之后, then()
的逻辑才会被执行。
为此,我建议您重组逻辑,以便loadRemoteFile()
本身返回promise,这样就可以解决它,而无需将其作为参数传递。 尝试这个:
$(document).ready(function() { function kickOff() { return loadRemoteFile("hconfig.js"); } function loadRemoteFile(filename) { return new Promise(function(resolve, reject) { console.log('loading remote file...'); // your logic here... setTimeout(function() { // pretend this is an AJAX request.... console.log('remote file loaded.'); resolve(); // resolve the promise here to signify all work has been completed }, 2000); }); } kickOff().then(function(result) { console.log('kickoff...'); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
请注意,如果在远程调用过程中遇到错误,也可以在Promise处理程序中调用reject()
。
或者,您可以更改逻辑以使用回调模式。 这样就不需要Promise和中介的kickOff()
方法:
$(document).ready(function() { function loadRemoteFile(filename, cb) { console.log('loading remote file...'); // your logic here... setTimeout(function() { // pretend this is an AJAX request.... console.log('remote file loaded.'); cb && cb(); }, 2000); } loadRemoteFile("hconfig.js", function(result) { console.log('kickoff...'); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.