Is there any mean to make this more elegant using other solutions (jquery is fine)?
Important in my case is that respective executions are only triggered if the previous ones have been terminated.
seqExe(["item one", "item two", "item three", "item four", "item five"])
function seqExe(corpus) {
var i = -1,
len = corpus.length,
defer = jQuery.Deferred(),
promise = defer.promise();
while(++i < len) {
promise = promise.then((function(item) {
return function() {
console.log(item);
return foo(item);
}
}).call(this, corpus[i]));
}
promise.then(function() {
console.log("Done");
}, function() {
console.error("Failed");
});
return defer.resolve();
}
function foo(item) {
var defer = jQuery.Deferred();
window.setTimeout(
function() {
defer.resolve()
console.log(item);
}, Math.random() * 2000 + 1000);
return defer.promise();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
Supposed output should be:
item one
item one
item two
item two
item three
item three
item four
item four
item five
item five
Done