summaryrefslogtreecommitdiff
path: root/lib/retry.js
blob: aecd07fffdced73112c7f5b93331c52caa035d02 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
'use strict';

import series from './series';
import noop from 'lodash/noop';

export default function retry(times, task, callback) {
    var DEFAULT_TIMES = 5;
    var DEFAULT_INTERVAL = 0;


    var opts = {
        times: DEFAULT_TIMES,
        interval: DEFAULT_INTERVAL
    };

    function parseTimes(acc, t) {
        if (typeof t === 'object') {
            acc.times = +t.times || DEFAULT_TIMES;
            acc.interval = +t.interval || DEFAULT_INTERVAL;
        } else if (typeof t === 'number' || typeof t === 'string') {
            acc.times = +t || DEFAULT_TIMES;
        } else {
            throw new Error("Invalid arguments for async.retry");
        }
    }


    if (arguments.length < 3 && typeof times === 'function') {
        callback = task || noop;
        task = times;
    } else {
        parseTimes(opts, times);
        callback = callback || noop;
    }


    if (typeof task !== 'function') {
        throw new Error("Invalid arguments for async.retry");
    }


    var attempts = [];
    while (opts.times) {
        var isFinalAttempt = !(opts.times -= 1);
        attempts.push(retryAttempt(isFinalAttempt));
        if (!isFinalAttempt && opts.interval > 0) {
            attempts.push(retryInterval(opts.interval));
        }
    }

    series(attempts, function(done, data) {
        data = data[data.length - 1];
        callback(data.err, data.result);
    });


    function retryAttempt(isFinalAttempt) {
        return function(seriesCallback) {
            task(function(err, result) {
                seriesCallback(!err || isFinalAttempt, {
                    err: err,
                    result: result
                });
            });
        };
    }

    function retryInterval(interval) {
        return function(seriesCallback) {
            setTimeout(function() {
                seriesCallback(null);
            }, interval);
        };
    }
}