Recursion and shifting through an array of functions (asynchronously)

JS
S
JavaScript

Recursion and shifting through the Array of Functions Move only to the next function when previous function has completed

1const steps = [
2    (link, cb) => {
3      console.log('first step',link);
4      cb();
5    },
6    (link, cb) => {
7        console.log('second step',link);
8        cb();
9    },
10    (link, cb) => {
11        // async
12        setTimeout((link) => {
13            // POST todo..
14            console.log('final step', link);
15                cb();
16        }, 50);
17    }
18];
19
20const data = 'http://www.google.pt';
21
22
23function runSerial(steps, data, done) {
24    // Recursion
25    function runSteps(steps, data, done) {
26        if (steps.length === 0) {
27            return done();
28        }
29
30        // First item of the array
31        var step = steps.shift();
32
33        function next() {
34            // run asynchronously after finishing current execution block (stack overflow preventer)
35            setTimeout(function () {
36                runSteps(steps, data, done);
37            },0);
38        }
39
40        // Flow Control
41        step(data, function (err) {
42            if (err) {
43                return done(err);
44            }
45  
46            // recursion
47            next();
48        })
49    }
50
51    // Entry point
52    runSteps(steps, data, done)
53}
54
55runSerial(steps, data, (err)=>{
56    console.log('completed', err);
57});

Created on 12/5/2017