: ? , .
, .
, , . callDef:
[func, arg1, arg2, arg3]
, :
[waste, 5]
:
function call(callDef) {
return callDef[0].apply(null, callDef.slice(1));
}
callDef, , callInParallel, callDefs:
[callInParallel, [callDef, callDef]]
[ callInParallel, [[waste, 5], [waste, 4]] ],
callInParallel :
function callInParallel(callDefs) {
return $.when.apply($, callDefs.map(call));
}
, callDefs:
[
[ callInParallel, [[waste, 5], [waste, 4]] ],
[ callInParallel, [[waste, 3], [waste, 2]] ],
[ callInParallel, [[waste, 1], [waste, 0]] ]
]
callDefs call callInParallel.
- callInSequence, callDef .
callInParallel , callDef: wait .then(). wait , .
, $.when, , -, :
function callInSequence(callDefs) {
var wait = $.Deferred().resolve();
return $.when.apply($, callDefs.map(function (callDef) {
return wait = wait.then(function () {
return call(callDef);
});
}));
}
, Def:
[
callInSequence, [
[ callInParallel, [[waste, 5], [waste, 4]] ],
[ callInParallel, [[waste, 3], [waste, 2]] ],
[ callInParallel, [[waste, 1], [waste, 0]] ]
]
]
:
function waste(secs) {
var result = $.Deferred();
setTimeout(function () {
$('body').append('<div>'+secs+'</div>');
result.resolve('done ' + secs);
}, secs * 1000);
return result.promise();
}
function call(callDef) {
return callDef[0].apply(null, callDef.slice(1));
}
function callInParallel(callDefs) {
return $.when.apply($, callDefs.map(call));
}
function callInSequence(callDefs) {
var wait = $.Deferred().resolve();
return $.when.apply($, callDefs.map(function (callDef) {
return wait = wait.then(function () {
return call(callDef);
});
}));
}
var everything = [
callInSequence, [
[ callInParallel, [[waste, 5], [waste, 4]] ],
[ callInParallel, [[waste, 3], [waste, 2]] ],
[ callInParallel, [[waste, 1], [waste, 0]] ]
]
];
call(everything).done(function () {
$('<hr>').appendTo('body');
$('<pre>', {text: JSON.stringify(arguments, null, 2)}).appendTo('body');
}).fail(function (error) {
console.log(error);
});
$('<div>sequence has started...</div>').appendTo('body');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
Hide result:
- jQuery 1.8+, , - , Deferreds 1.8.
-:
var everything = [
callInSequence, [
[ callInSequence, [[waste, 5], [waste, 4]] ],
[ callInParallel, [[waste, 3], [waste, 2]] ],
[ callInSequence, [[waste, 1], [waste, 0]] ]
]
];
thisArg , (window). . , .bind(), callDef.