简体   繁体   English

Express app.listen 返回 Promise { 服务器 {} }

[英]Express app.listen returns Promise { Server {} }

I have an express server running, I am running into an issue while writing unit tests.我有一个快速服务器正在运行,我在编写单元测试时遇到了问题。 I have a startup function that connects to database, then returns a Server with app.listen().我有一个启动 function 连接到数据库,然后返回一个带有 app.listen() 的服务器。 The issue is that if I return app.listen from within an async function, I get a Promise with a server inside of it, I have tried to resolve this promise, wait for this promise, return a server from.then(). The issue is that if I return app.listen from within an async function, I get a Promise with a server inside of it, I have tried to resolve this promise, wait for this promise, return a server from.then(). I do not want the promise I want the server.我不想要 promise 我想要服务器。

express.ts快递.ts

import express from 'express';

const app = express();

export { app };

startup.ts启动.ts

import { app } from './express';
import { sequelize } from './sequelize';

app._startup = (async() => {
  switch (process.env.NODE_ENV) {
    case "production":
      await sequelize.authenticate();
      break;
    case "test":
      await sequelize.sync({ force: true });
      break;
    case "development":
    default:
      await sequelize.sync({ force: false });
      break;
  }
})().then(() => true);

export { app };

server.ts服务器.ts

import { app } from './startup';

// export const server = app.listen(8080); // This works

export const server = (
  async() => {
    await app._startup;
    return app.listen(8080); // This does not work
  }
)();

Because the Server {} is inside a Promise {} my unit tests all fail因为服务器 {} 在 Promise {} 内,所以我的单元测试都失败了

console.log(server);
// => Promise { Server { } }

How can I resolve this promise before exporting the server?在导出服务器之前如何解决这个 promise?

You can wait for the function to complete the async task.您可以等待 function 完成async任务。 Since you are defining server as an async function you can use await keyword to wait for it to complete.由于您将server定义为async function 您可以使用await关键字等待它完成。 Implementation is as follows:实施如下:

import { app } from './startup';

export const server = app.listen(8080);
export const server = await (  // use await to wait
  async() => {
    await app._startup;
    return app.listen(8080); // This does not work
  }
)();

Thanks for your comment @jfriend00感谢您的评论@jfriend00

The solution is posted below解决办法贴在下面

const server = createServer(app);

(async() => {
  await app._startup;
})().then(() => server.listen(8080));

export { server };

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

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