I need to run an arbitrary number of scripts. The next one can run only of the previous has loaded and executed. I know RequireJS (and related) would be the correct choice, but I’m trying to learn about promises, so this is my experiment:
var files = [
'first.js',
'second.js',
'third.js',
'fourth.js'
];
var funcs = files.map(function(file) {
return function() { return $.getScript(file); }
});
var deferred = $.Deferred();
funcs.reduce(function (soFar, f) {
return soFar.then(f);
}, deferred.resolve(funcs[0]));
Can someone elaborate about the pitfalls and alternatives to my solution?
What you’re really looking for is .pipe ( or in 1.8+, I believe .then was changed to mean the same thing )
In short, pipe will allow you to chain promises in the way that you’re looking for. The code might look something like this ( untested ):
** Edit **
With that link you provided, I understand what you were trying to accomplish. Here’s a corrected version of your solution with some comments. It accomplishes the same thing as the other solution, however it’s a much more concise version: