mirror of
https://github.com/apache/cordova-android.git
synced 2025-03-16 16:51:02 +08:00
refactor(retry): simplify retryPromise using modern JS (#1086)
This commit is contained in:
parent
5d3591b853
commit
e125ab1b9a
34
bin/templates/cordova/lib/retry.js
vendored
34
bin/templates/cordova/lib/retry.js
vendored
@ -21,7 +21,7 @@
|
|||||||
|
|
||||||
var events = require('cordova-common').events;
|
var events = require('cordova-common').events;
|
||||||
|
|
||||||
/*
|
/**
|
||||||
* Retry a promise-returning function a number of times, propagating its
|
* Retry a promise-returning function a number of times, propagating its
|
||||||
* results on success or throwing its error on a failed final attempt.
|
* results on success or throwing its error on a failed final attempt.
|
||||||
*
|
*
|
||||||
@ -31,31 +31,13 @@ var events = require('cordova-common').events;
|
|||||||
*
|
*
|
||||||
* @returns {Promise}
|
* @returns {Promise}
|
||||||
*/
|
*/
|
||||||
module.exports.retryPromise = function (attemptsLeft, promiseFunction) {
|
module.exports.retryPromise = async function (attemptsLeft, promiseFunction, ...args) {
|
||||||
// NOTE:
|
while (true) {
|
||||||
// get all trailing arguments, by skipping the first two (attemptsLeft and
|
try {
|
||||||
// promiseFunction) because they shouldn't get passed to promiseFunction
|
return await promiseFunction(...args);
|
||||||
var promiseFunctionArguments = Array.prototype.slice.call(arguments, 2);
|
} catch (error) {
|
||||||
|
if (--attemptsLeft < 1) throw error;
|
||||||
return promiseFunction.apply(undefined, promiseFunctionArguments).then(
|
|
||||||
// on success pass results through
|
|
||||||
function onFulfilled (value) {
|
|
||||||
return value;
|
|
||||||
},
|
|
||||||
|
|
||||||
// on rejection either retry, or throw the error
|
|
||||||
function onRejected (error) {
|
|
||||||
attemptsLeft -= 1;
|
|
||||||
|
|
||||||
if (attemptsLeft < 1) {
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
|
|
||||||
events.emit('verbose', 'A retried call failed. Retrying ' + attemptsLeft + ' more time(s).');
|
events.emit('verbose', 'A retried call failed. Retrying ' + attemptsLeft + ' more time(s).');
|
||||||
|
|
||||||
// retry call self again with the same arguments, except attemptsLeft is now lower
|
|
||||||
var fullArguments = [attemptsLeft, promiseFunction].concat(promiseFunctionArguments);
|
|
||||||
return module.exports.retryPromise.apply(undefined, fullArguments);
|
|
||||||
}
|
}
|
||||||
);
|
}
|
||||||
};
|
};
|
||||||
|
Loading…
x
Reference in New Issue
Block a user