NodeJS传递一个额外的参数到回调 [英] NodeJS passing an extra param to a callback

查看:542
本文介绍了NodeJS传递一个额外的参数到回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Node.JS的开始,作为第一次尝试,我实现一个小的url缩短服务,将获得一个id参数的请求,并在搜索一个cassandra数据库后重定向到实际的url。
下面你可以找到我的实现。

I'm a begginer in Node.JS and as a first tryout i'm implementing a small url shortening service that will get a request with an id parameter and redirect to the actual url after searching a cassandra database. Below you can find my implementation.

var reqResponse;

app.get('/r/:id', function(req, res) {
    reqResponse = res;
    conn.connect(function(err, keyspace) {
        if(err){
            throw(err);
        }
        conn.cql(cqlSelectStatement, [req.params.id], { gzip:true }, redirectCallback);
    });

});

function redirectCallback (err, results) {
    if (err != null) {
        //log
    } else {
        if (results.length > 0) {
            results.every(function(row){
                reqResponse.writeHead(config.redirectStatus, {
                    'Location': row[0].value
                });
                reqResponse.end();
                return false;
            });
        } else {
            reqResponse.send("There was a problem!");
            return false;
        }
    }
    conn.close();
    return true;
}

它工作正常,它做的工作,但我有一些疑问关于该reqResponse全局变量。我不喜欢它。
有一种方法我可以发送res作为redirectCallback函数的参数?

It works fine, it does the job, but i'm having some doubts about that reqResponse "global" variable. I don't like it there. Is there a way I could send "res" as a parameter to the redirectCallback function?

谢谢!

推荐答案

是的:创建一个匿名函数,并使用它传递参数:

Yes there is: Create an anonymous function and use that to pass the parameter:

app.get('/r/:id', function(req, res) {
    conn.connect(function(err, keyspace) {
        if(err){
            throw(err);
        }
        conn.cql(cqlSelectStatement, [req.params.id], { gzip:true }, function (err, results) { redirectCallback(err, res, results); } );
    });

});

您的回调变为:

function redirectCallback (err, res, results) {

这篇关于NodeJS传递一个额外的参数到回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆