javascriptnode.jsasynchronouswaterfall

async.waterfall not acting synchronously


I'm trying to write a header of an MD5 hash token using crypto then return it back as a response. For some reason, it isn't actually running synchronously. I know JS is an asynchronous language, and that's really the only part I'm struggling with right now. Any help would be appreciated.

This is what I have so far:

const crypto = require('crypto');
const bodyParser = require('body-parser');
const formidable = require('formidable');
const async = require('async')

app.post('/pushurl/auth', (req, res) =>
    var data = req.body.form1data1 + '§' + req.body.form1data2 
        

    async.waterfall([
            function(callback) {
                var token = crypto.createHash('md5').update(data).digest("hex");
                callback(null, token);
            },
            function(token, callback) {
                res.writeHead(301,
                    {Location: '/dashboard?token=' + token}
                );
                callback(null)
            },
            function(callback) {
                res.end();
                callback(null)
            }
        ]);
        
    }
});

Output:

Uncaught Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
<node_internals>/internal/errors.js:256
    No debugger available, can not send 'variables'
Process exited with code 1

Solution

  • JavaScript is an asynchronous language, yes, but it can also do synchronous tasks very well. In your case, you don't need to do any async expect if you're dealing with promises.

    If you write your code like in the example below it will just execute from top to bottom.

    But the error (probably) occurred because you forgot to add an opening curly brace to your app.post callback, which results in the data var being immediately returned because of an implied return statement () => (implied), () => {} (explicit).

    const crypto = require('crypto');
    const bodyParser = require('body-parser');
    const formidable = require('formidable');
    
    app.post('/pushurl/auth', (req, res) => {
    
      const data = req.body.form1data1 + '§' + req.body.form1data2;
      const token = crypto.createHash('md5').update(data).digest("hex");
      res.writeHead(301, {
        Location: '/dashboard?token=' + token
      });
      res.end();
            
    });