Attempt tries to resolve promises
Attempt tries to resolve promises.
- Can try to get valuable data from server over unstable mobile networks.
- Can handle some unexpected network lags with 0 code or timeouts.
For example, user of your service have some critical data and you want to deliver it to your server. User browsing under unstable and slow cellular network. You may give up on first fail or try to fix this problem, using callback hell or use this solution :)
Assume you have rule which defines behaviour of repeating requests:
- each next repeat should be performed in
N * 500ms, where N is attempt number
error.status >= 500- no reason to repeat, your service is totally down
error.status === 400- no reason to repeat, something wrong with input data
error.status === 0(aka abort) - repeat
- if number of repeats is more than 5 - ask user continue to repeat or not
- if number of repeats is more than 10 - do not repeat
And instead of calling promise directly
$getJSON'/json'thenresolve reject progress;
wrap it with
return $getJSON'/json';// no reason to repeatif err && errstatus === 400 || errstatus >= 500return false;// if number of repeats is more than 10 - do not repeatif attemptNo > 10return false;// if number of repeats is more than 5 - ask user what repeat or notif attemptNo > 5return askUserWhatToDopipereturn attemptNo * 500;;// each next repeat should be performed in N * 500msreturn attemptNo * 500;thenresolve reject progress;
Attempt tries to use global Promises, but you can specify your own promises.
Or use old-style promises approach:
attemptconfigurevar dfd = $Deferred;tryhandlerdfdresolve dfdreject dfdprogress;catch edfdrejecte;return dfdpromise;;
attemptreturn $getJSON'/json';// if not timeout (null)// and 0 < status < 500 - no reason to continueif err && errstatus > 0 && errstatus < 500return false || null || void 0;// To many attempts - network or server totally downif attemptNo > 5return false;// repeat request in N * 2000 msreturn attemptNo * 2000;thenresolve reject progress;return processDatadata;console.log'I tried several times... and fail :(' error;console.log'Failed to load, retrying...' error attemptNo;
attemptreturn $getJSON'/json';setTimeoutdecideMathrandom > 0.5 ? true : false;1000thenresolve reject progress;
attemptreturn $getJSON'/json';// askUserWhatToDo - a Promise factoryreturn askUserWhatToDoerr attemptNo;thenresolve reject progress;
attempt// pass attempt to server (for logging)return $getJSON'/json?attempt=' + attemptNo;// askUserWhatToDo - a Promise factoryreturn askUserWhatToDoerr attemptNo;thenresolve reject progress;