Created
September 3, 2016 14:37
-
-
Save gaogao-9/199cd8a4107a737786a6df97e8e8f923 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
documentReady() | |
.then(loopDfd([initXxxDB, xxxDBReady], xxxDBError)) | |
.then(xxxTask) | |
.fail(uncaughtError); | |
// deferredがresolveされるまで、restartCallbackを挟みながら処理を繰り返すメソッド。 | |
// 第一引数には配列もしくは配列を返す関数を渡すことが出来る。 | |
function loopDfd(actorDfdList, restartCallback){ | |
if(typeof(actorDfdList) === "function") actorDfdList = actorDfdList(); | |
return function loop(){ | |
return new $.Deferred(function(dfd){ | |
var actorDfd = new $.Deferred().resolve(); | |
for(var i=0;i<actorDfdList.length;i++){ | |
actorDfd = actorDfd.then(actorDfdList[i]); | |
} | |
actorDfd | |
.then(function(){ | |
return dfd.resolve(); | |
}, function(){ | |
return restartCallback.apply(this, arguments) | |
.then(loop); | |
}) | |
.fail(function(){ | |
return dfd.reject(); | |
}); | |
}).promise(); | |
} | |
} | |
function documentReady(){ | |
return new $.Deferred(function(dfd){ | |
jQuery(function(){ | |
// jQuery 3.0未満では、readyイベントが非同期で実行される保証がされていないため、0秒遅延する | |
setTimeout(function(){ | |
dfd.resolve(); | |
}, 0); | |
}); | |
}).promise(); | |
} | |
var count = 0; | |
function initXxxDB(){ | |
// DB初期化(1回目は失敗し、2回目は成功する) | |
return new $.Deferred(function(dfd){ | |
(count++) ? dfd.resolve("ready") : dfd.reject("error"); | |
}).promise(); | |
} | |
var _db = null; | |
function xxxDBReady(db){ | |
_db = db; | |
alert("xxxdbReady"); | |
return new $.Deferred().resolve(db); | |
} | |
function xxxDBError(err){ | |
alert("xxxDBError"); | |
// 500ms後にもう一回チャレンジ | |
return new $.Deferred(function(dfd){ | |
setTimeout(function(){ | |
dfd.resolve(); | |
}, 500); | |
}).promise(); | |
} | |
function xxxTask(db){ | |
// ここでやりたいことをやる | |
} | |
function uncaughtError(err){ | |
// 予期しないエラーが発生した時はここでキャッチできる | |
alert("uncaughtError"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment