arnaucube
arnaucube/commonroutesServerPublic Self-hosted repository
commonroutesServer/www/platforms/android/cordova/lib/retry.js
www/platforms/android/cordova/lib/retry.jsRaw
 1#!/usr/bin/env node
 2
 3/*
 4    Licensed to the Apache Software Foundation (ASF) under one
 5    or more contributor license agreements.  See the NOTICE file
 6    distributed with this work for additional information
 7    regarding copyright ownership.  The ASF licenses this file
 8    to you under the Apache License, Version 2.0 (the
 9    "License"); you may not use this file except in compliance
10    with the License.  You may obtain a copy of the License at
11
12      http://www.apache.org/licenses/LICENSE-2.0
13
14    Unless required by applicable law or agreed to in writing,
15    software distributed under the License is distributed on an
16    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17    KIND, either express or implied.  See the License for the
18    specific language governing permissions and limitations
19    under the License.
20*/
21
22/* jshint node: true */
23
24'use strict';
25
26var events = require('cordova-common').events;
27
28/*
29 * Retry a promise-returning function a number of times, propagating its
30 * results on success or throwing its error on a failed final attempt.
31 *
32 * @arg {Number}   attemts_left    - The number of times to retry the passed call.
33 * @arg {Function} promiseFunction - A function that returns a promise.
34 * @arg {...}                      - Arguments to pass to promiseFunction.
35 *
36 * @returns {Promise}
37 */
38module.exports.retryPromise = function (attemts_left, promiseFunction) {
39
40    // NOTE:
41    //      get all trailing arguments, by skipping the first two (attemts_left and
42    //      promiseFunction) because they shouldn't get passed to promiseFunction
43    var promiseFunctionArguments = Array.prototype.slice.call(arguments, 2);
44
45    return promiseFunction.apply(undefined, promiseFunctionArguments).then(
46
47        // on success pass results through
48        function onFulfilled(value) {
49            return value;
50        },
51
52        // on rejection either retry, or throw the error
53        function onRejected(error) {
54
55            attemts_left -= 1;
56
57            if (attemts_left < 1) {
58                throw error;
59            }
60
61            events.emit('verbose', 'A retried call failed. Retrying ' + attemts_left + ' more time(s).');
62
63            // retry call self again with the same arguments, except attemts_left is now lower
64            var fullArguments = [attemts_left, promiseFunction].concat(promiseFunctionArguments);
65            return module.exports.retryPromise.apply(undefined, fullArguments);
66        }
67    );
68};