繁体   English   中英

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

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

我有一个快速服务器正在运行,我在编写单元测试时遇到了问题。 我有一个启动 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(). 我不想要 promise 我想要服务器。

快递.ts

import express from 'express';

const app = express();

export { app };

启动.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 };

服务器.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
  }
)();

因为服务器 {} 在 Promise {} 内,所以我的单元测试都失败了

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

在导出服务器之前如何解决这个 promise?

您可以等待 function 完成async任务。 由于您将server定义为async function 您可以使用await关键字等待它完成。 实施如下:

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

感谢您的评论@jfriend00

解决办法贴在下面

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