我在使用 jQuery 同步加载脚本和执行脚本时遇到问题。
我所拥有的看起来与此类似:
// Load Libraries in 'when'
$.when(
loadJSFile("lib1.js"),
loadJSFile("lib2.js")
loadJSFile("lib3.js")
).then(function() {
// Load JS files that use the library files
loadJSFile("file1.js");
loadJSFile("file2.js");
loadJSFile("file3.js");
// needs to return deferred object...
}).then(function() {
// Call functions declared in file1, file2 and file3
func1();
func2();
func3();
});
loadJSFile 通过 $.getScript 加载一个 javascript 文件,如果它还没有包含在 DOM 中,返回 $.getScript Promise,或者不返回任何东西,如果它已经包含。
我认为第一个 then 调用必须返回一个 Promise/Deferred,但我该如何处理 3 个 Deferred 对象?
上面的代码在加载 file1 到 file3 之前调用了 3 个函数(func1、func2 和 func3)...
最佳答案
I think the first then call has to return a Promise/Deferred, but how do I do that with 3 Deferred objects?
您已经为第一组脚本执行此操作 - $.when
返回一个 promise ,该 promise 在其所有 promise 参数都已解决时解决。
你也应该将它用于第二组:
$.when(
loadJSFile("lib1.js"),
loadJSFile("lib2.js")
loadJSFile("lib3.js")
).then(function() {
// Load JS files that use the library files
return $.when(
loadJSFile("file1.js"),
loadJSFile("file2.js"),
loadJSFile("file3.js")
)
}).then(function() {
// Call functions declared in file1, file2 and file3
func1();
func2();
func3();
});
但是,由于您显然将其用于异步脚本加载,因此您可能需要研究更完整的解决方案,例如 RequireJS .
关于javascript - 然后jquery多个deferreds,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30162102/