简体   繁体   English

如何从全局 scope 访问回调中的值?

[英]How to access a value inside the callback from the global scope?

I'm using express Js and I want to export the port on which the server is running for some testing purpose.我正在使用 express Js,并且我想导出服务器正在运行的端口以用于某些测试目的。 But the port seems to be only available inside callback function of app.listen .Is there any way I can export the port?但是该端口似乎仅在 app.listen 的回调 function 中app.listen 。有什么办法可以导出端口吗?

let server = app.listen(3000, 'localhost', ()=>{
let port = server.address().port;
})
// accesss port here
module.export = port; // what I want

You could put a Promise as the export which resolves to the port:您可以将 Promise 作为解析为端口的导出:

module.exports.portProm = new Promise((resolve) => {
  const server = app.listen(3000, 'localhost', () => {
    resolve(server.address().port);
  });
});

and do

require('server.js').portProm.then((port) => {
  // use port here
});

Since the first parameter is the port the server should listen to, why not just pass a specific port in the first place?既然第一个参数是服务器应该监听的端口,为什么不首先传递一个特定的端口呢?

const port = 3042;
let server = app.listen(port, 'localhost');

module.exports = port;

edit编辑

~~Defining the variable outside the callback should do the trick:~~ ~~在回调之外定义变量应该可以解决问题:~~

It doesn't, because the app resolves asynchronously.它没有,因为应用程序异步解析。

let port;

let server = app.listen(3000, 'localhost', () => {
    port = server.address().port;
});

// accesss port here
module.exports = port;

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

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