Sequence.js

Syntax

Constructor

let sqnc = new Sequence();

Methods

sqnc.step( ... );

Adds a step to the sequence.

sqnc.run( [ array initArgs] );

Runs the sequence and returns a Promise-like object.

Chaining

(new Sequence())
.step(...)
.step(...)
.step(...)
...
.run().then(...).catch(...);

Method .step()

sqnc.step( array args );

The step() function expects arrays only as argument. If the argument is not an array it will be casted to one. E.g. sqnc.step("Hello world"); will become sqnc.step(["Hello world"]);

Step by value

// will pass ["Hello World"] to next step
sqnc.step(["Hello world"]);

Step by wrapper

sqnc.step((args) => {
    // args is a list of returned values by previous step.
});

Single callback

(new Sequence())
.step((args) => {
    return (cb) => {
        setTimeout(cb, 1000);
    };
})
.run();

Promise-like callbacks

(new Sequence())
.step((args) => {
    return (resolve, reject) => {
        setTimeout(() => {
            try {
                ...
                resolve();
            } catch (e) {
                reject(e);
            }
        }, 1000);
    };
})
.run();

(!) Callbacks only work once

(new Sequence())
.step((args) => {
    return (resolve, reject) => {
        resolve("this is ok");
        resolve("this will not work");
        reject("this wont work either");
        return "Nor this...";
    };
})
.step((args) => {
    console.log(args[0]);
})
.run();

Step arguments

sqnc.step((args) => {
    // this wrapper returns nothing
    // it will pass [undefined] to next step
});

sqnc.step((args) => {
    // will return ["Hello World"] to next step
    return "Hello World"; // will be converted to array
});

sqnc.step((args) => {
    // will return ["Hello", "World"] to next step
    return ["Hello", "World"];
});

Wrapper returning functions

sqnc.step((args) => {
    // will pass [1] to next step
    return 1;
});

sqnc.step((args) => {
    // will pass [2] to next step
    return () => {
        return 2;
    };
});

sqnc.step((args) => {
    // will pass [3] to next step
    return (cb) => {
        cb(3);
    };
});

sqnc.step((args) => {
    // will pass [4] to next step
    return (resolve, reject) => {
        resolve(4);
    };
});

sqnc.step((args) => {
    // will pass [5, 6, 7, 8] to next step
    return [
        5,
        () => { return 6; },
        (cb) => { cb(7); },
        (resolve, reject) => { resolve(8); }
    ];
});