简体   繁体   English

async.waterfall 不同步运行

[英]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.我正在尝试使用加密编写 MD5 哈希令牌的标头,然后将其作为响应返回。 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.我知道 JS 是一种异步语言,这真的是我现在唯一在努力的部分。 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

JavaScript is an asynchronous language, yes, but it can also do synchronous tasks very well. JavaScript 是一种异步语言,是的,但它也可以很好地完成同步任务。 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).但是错误(可能)发生是因为您忘记在app.post回调中添加app.post花括号,导致data var 立即返回,因为隐含的返回语句() => (implied), () => {} (显式)。

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();
        
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM