从一个函数返回值到另一个函数

时间:2015-06-19 07:15:40

标签: javascript node.js

我使用以下代码,我的问题是我应该如何将端口从第一个函数传递到seconde,我知道如果我调用第二个函数内部,我可以做到第一个但是还有其他方法可以使用吗?

 portscanner.findAPortNotInUse(3000, 3010, '127.0.0.1', function(error, port) {
        console.log('AVAILABLE PORT AT: ' + port)
    });

    http.createServer(function (req, res) {
        res.writeHead(200, { 'Content-Type': 'text/plain' });
   JSON.stringify(req.headers, true, 2));
        res.end();
    }).listen(9033);

而不是使用端口9033我想使用第一个...

中的值

4 个答案:

答案 0 :(得分:1)

端口扫描程序方法是异步,因此唯一的方法是在确定可用端口时,在调用回调函数时创建服务器:

portscanner.findAPortNotInUse(3000, 3010, '127.0.0.1', function(error, port) {
    console.log('AVAILABLE PORT AT: ' + port)
    http.createServer(function (req, res) {
      // ...
    }).listen(port);
});

答案 1 :(得分:1)

您正在处理异步代码。尝试

portscanner.findAPortNotInUse(3000, 3010, '127.0.0.1', function(error, port) {
    console.log('AVAILABLE PORT AT: ' + port);

    http.createServer(function (req, res) {
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        JSON.stringify(req.headers, true, 2));
        res.end();
    }).listen(port);

});

如果您不想在回调中运行createServer部分,则另一个选项是使其成为函数调用。除了改变语法

之外,这并没有真正做任何事情
portscanner.findAPortNotInUse(3000, 3010, '127.0.0.1', function(error, port) {
    console.log('AVAILABLE PORT AT: ' + port);

    // call the 'CreateServer' function with the available port
    CreateServer(port);
});

function CreateServer (port) {
     http.createServer(function (req, res) {
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        JSON.stringify(req.headers, true, 2));
        res.end();
    }).listen(port);
}

答案 2 :(得分:1)

File Path

试试这段代码。

答案 3 :(得分:-1)

第一种方法返回什么类型?您可以简单地将其设置为String并将其结果设置为将在类中定义的私有String变量。然后你只想这样做:

<强>听(this.port);

或者,您可以设置 final static String 变量端口,该端口将作为参数传递给两个方法。

相关问题