Husky Husky - 4 months ago 11
Node.js Question

How to re-post (re-start) the POST function in Node.js

Environment



My environment : Node.js with Express 4.0

Main library : Async.js

When I use the async programming. In some IF/ELSE-statements have to restart this function, but I cannot do it.




app.post('/postpage', function (req, res) {
async.waterfall([
// A part.
function (callback) {
// Here will do something.
callback(null, a);
},
// B part.
function (a, callback) {
// Here will do something.
callback(null, a, b);
},
// C part.
function (a, b, callback) {
if (....) {
// Here will do something.
callback(null, a, b, c);
else {
// Here need to jump to 'A part' and run.
}
},
], function (err, ...) {
...
});
});





Problem



// Here need to jump(or return) to 'A part' and run.
, this line in above code. How to write the code to complete it.

Answer

So what you're asking for is recursion. Though you need to be careful as JavaScript does not have tail call optimization, so eventually your stack will overflow. Anyhow, this should do it:

app.post('/postpage', function (req, res) {
    recurWaterfall = function(finalCallback) {
        async.waterfall([
            // A part.
            function (callback) {
                // Here will do something.
                callback(null, a);
            },
            // B part.
            function (a, callback) {
                // Here will do something.
                callback(null, a, b);
            },
            // C part.
            function (a, b, callback) {
                if (....) {
                    // Here will do something.
                    callback(null, a, b, c);
                else {
                    // Here need to jump to 'A part' and run.
                    recurWaterfall(callback)
                }
            },
        ], function (err, ...) {

            // You must call this
            finalCallback(err, ....)
        });
    }

    // Call your waterfall the first time
    recurWaterfall(function(err, ...){
        // Whatever to do after waterfall is finished

    })
});