$(function() {
$.when(Step1).then(function() {
$.when(Step2).then(Step3);
});
});
エラー処理については、Stepn を次のように書き換えることをお勧めします。
function Stepn() {
return $.ajax(<foo>).fail(function() {
// handle failure
});
}
この形式でコールバックを使用すると、必要なことを行うことができます。5 つ以上のステップがある場合、インデントが混乱するため、このためのキューを作成する価値があるかもしれません。
これがライブの例です
var Queue = function() {
var q = [];
var that = this;
// If items in queue then run them.
function moveNext() {
if (q.length > 0) {
that.runItem();
}
}
// run first item in queue
this.runItem = function() {
// get item
var item = q.shift();
// when deferred object then run then ...
$.when(item.item).then([item.options.done, function() {
// item finished, move to next.
moveNext();
}], [item.options.fail, function() {
// if run item always then move next on failure.
if (item.options.always) {
moveNext();
}
}]);
};
this.add = function(def, options) {
// if array then call add on each item in array
if ($.isArray(def)) {
for (var d in def) {
this.add(d, options);
}
// return as we are done.
return this;
}
// push item onto array
q.push({
item: def,
options: options
});
// if items & not delay then run item.
if (q.length === 1 && !options.delay) {
this.runItem();
}
// enable jQuery style chaining \o/
return this;
};
};
Queue.add([def, def, ...], options)
遅延アイテムまたは遅延アイテムの配列をキューに追加します。単一の遅延アイテムまたは配列のいずれかで使用できます。オプションマップは次のとおりです
{
"delay" : Boolean, // if true do not run the item in the queue after appending it.
"done" : Function, // optional done call back
"fail" : Function, // optional fail call back
"always": Boolean // if true run the next item in the queue even if this item fails.
}
Queue.runItem
、キュー内の次のアイテムを実行する関数。内部で呼び出され、遅延プロパティと連結して手動で使用できます。