Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery multiple deferreds in then

I have a problem synchronizing the loading of scripts and executing them with jQuery.

What I have looks similiar to this:

// 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 loads a javascript file via $.getScript, if it's not already included in in the DOM, returning the $.getScript Promise, or not returning anything, if it's already included.

I think the first then call has to return a Promise/Deferred, but how do I do that with 3 Deferred objects?

The code above calls the 3 functions (func1, func2 and func3) before file1 to file3 are loaded...

like image 618
Johannes Avatar asked May 11 '15 07:05

Johannes


1 Answers

I think the first then call has to return a Promise/Deferred, but how do I do that with 3 Deferred objects?

You're already doing this for the first set of scripts - $.when returns a promise that resolves when all of its promise arguments have resolved.

You should use it for the second set as well:

$.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();
});

However, since you're apparently using this for async script loading, you may want to look into a more complete solution like RequireJS.

like image 152
joews Avatar answered Sep 19 '22 07:09

joews