【问题标题】:How to block server.js in node.js如何在 node.js 中阻止 server.js
【发布时间】:2019-11-27 15:38:29
【问题描述】:

问题陈述

我有 server.js,其中有一个配置文件

我的 server.js

  1. 一些导入

  2. 需要 config.js -> api 调用来获取配置 /promise 调用

  3. 服务器开始使用配置中的值

  4. 在我获得配置之前,服务器尝试启动并崩溃,因为配置为空。

如何阻止进程超越 config.js 步骤

【问题讨论】:

  • 请提供一个最小的代码示例,以便我们更好地了解根本问题是什么:)

标签: javascript node.js express async-await


【解决方案1】:

我不知道我是否完全理解你的情况。但是,如果您想在请求之后启动服务器,您可以使用 thenasync / await 来执行此操作。考虑一下这个简单的 sn-p:

const express = require('express');
const app = express();
const getConfig = require('./config');

const expressConfigs = (app, config) => {
  app.get('/', (req, res) =>  {
    res.send('Hello World!');
  });

  app.listen(config.port, () => {
    console.log(`Example app listening on port ${config.port}!`);
  });
};

(async () => {
  const config = await getConfig();
  expressConfigs(app, config);
})();


OBS: config soube export one Promise,你可以使用 node-fetch。

【讨论】:

    【解决方案2】:

    在实现承诺之前,您无法启动服务器,因此您实际上有一个非空配置。

    【讨论】:

      猜你喜欢
      • 2021-12-09
      • 2014-06-30
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 2021-04-14
      • 2013-06-24
      • 2013-07-07
      • 1970-01-01
      相关资源
      最近更新 更多