Skip to content

Instantly share code, notes, and snippets.

@DavidAnson
Created February 20, 2015 02:37
Show Gist options
  • Save DavidAnson/80c516c2067cc1375d83 to your computer and use it in GitHub Desktop.
Save DavidAnson/80c516c2067cc1375d83 to your computer and use it in GitHub Desktop.

Revisions

  1. DavidAnson created this gist Feb 20, 2015.
    43 changes: 43 additions & 0 deletions Qsequence.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    "use strict";

    var Q = require("q");

    // Worker function
    function logAndIncrement(val) {
    console.log(val);
    return val + 1;
    }

    // Normal
    Q(0)
    .then(function(v) {
    return Q(logAndIncrement(v));
    })
    .then(function(v) {
    return Q(logAndIncrement(v));
    })
    .then(function(v) {
    console.log(v);
    });

    // Slightly modified from https://github.com/kriskowal/q#sequences
    function Qsequence(initialValue, promises) {
    var result = Q(initialValue);
    promises.forEach(function(r) {
    result = result.then(r);
    });
    return result;
    }

    // With Qsequence
    Qsequence(0, [
    function(v) {
    return Q(logAndIncrement(v));
    },
    function(v) {
    return Q(logAndIncrement(v));
    },
    function(v) {
    console.log(v);
    }
    ]);