使用reduce with async并等待

时间:2017-10-18 16:45:59

标签: node.js typescript asynchronous promise

我知道其他帖子涵盖了这个主题但是我需要将它用作const,以便它只在运行时初始化

这是我的问题,我是nodejs的新手,并在网上搜索了很多。没有找到任何接近我需要的解决方案

const apis = ['log', 'get', 'all']

const loggers = apis.reduce(async (memo, api) => {
  try {
    await fs.stat(path.join(process.cwd() + config.application.log.dir, api));
  } catch (e) {
    await fs.mkdir(path.join(process.cwd() + config.application.log.dir, api));
  }
  memo[api] = new (winston.Logger)({
    transports: [
      new winston.transports.File({
        timestamp: () => (new Date().toLocaleTimeString()),
        datePattern: 'yyyy-MM-dd',
        level: config.application.mode === 'test' ? 'emerg' : 'info',
        filename: path.join(process.cwd(), config.application.log.dir, api, `${api}.log`),
        maxsize: 1024 * 1024 * 100, // 100MB
        colorize: false,
        prepend: true,
        json: false,
      }),
    ],
  });
  return await Promise.resolve(memo);
}, {});

我的问题是结果是Promise任何想法如何改变它?

编辑:-----------------------

我终于选择了这个解决方案,并在快速初始化期间从app.ts调用它(如果你有更好的想法,请不要犹豫,添加它):

export const loggerInitialisation = async function (): Promise<void> {

  // Create all log folders
  await Promise.all(apis.map(async (api) => {
    try {
      await fs.stat(path.join(process.cwd() + config.application.log.dir, api));
    } catch (e) {
      await fs.mkdir(path.join(process.cwd() + config.application.log.dir, api));
    }
  }));
  // Create for each log folder a winston logger and transport
  loggers = apis.reduce((memo, api) => {
    memo[api] = new (winston.Logger)({
      transports: [
        new winston.transports.File({
          timestamp: () => (new Date().toLocaleTimeString()),
          datePattern: 'yyyy-MM-dd',
          level: config.application.mode === 'test' ? 'emerg' : 'info',
          filename: path.join(process.cwd(), config.application.log.dir, api, `${api}.log`),
          maxsize: 1024 * 1024 * 100, // 100MB
          colorize: false,
          prepend: true,
          json: false,
        }),
      ],
    });
    return memo;
  }, {});
};

0 个答案:

没有答案