简体   繁体   English

在module.exports之前等待异步功能

[英]Await asynchronous function before module.exports

I have a NextJS app and am using next-routes to handle all routing. 我有一个NextJS应用,正在使用next-routes处理所有路由。

My routing module currently looks like this: 我的路由模块当前如下所示:

const routes = require('next-routes')();
const { getEntries } = require('../data/contentful');

module.exports = async () => {
  const globalSettings = await getEntries({
    content_type: 'globalSettings',
  });

  routes
    .add('caseStudies', `/${globalSettings.fields.caseStudiesSlug}`, 'caseStudies')
    .add('caseStudy', `/${globalSettings.fields.caseStudiesSlug]}/:slug`, 'caseStudy')
    .add('home', `/`, 'index')
    .add('page', `/:slug*`, 'page'));

  return routes;
};

I can get this working for server side, but to use next-routes on client side, I need this module to immediately return the routes object rather than an async function. 我可以在服务器端使用此功能,但是要在客户端使用下一个路由,我需要此模块立即返回路由对象,而不是异步函数。 eg 例如

const routes = require('next-routes')();
const { getEntries } = require('../data/contentful');

// Do this first, then module.exports
const globalSettings = await getEntries({
  content_type: 'globalSettings',
});

module.exports = routes
  .add('caseStudies', `/${globalSettings.fields.caseStudiesSlug}`, 'caseStudies')
  .add('caseStudy', `/${globalSettings.fields.caseStudiesSlug]}/:slug`, 'caseStudy')
  .add('home', `/`, 'index')
  .add('page', `/:slug*`, 'page'));

This doesn't work because await must be inside an async function. 这不起作用,因为await必须在异步函数中。 How can I complete my async API call before doing my module.exports of the routes object? 如何在执行路由对象的module.exports之前完成异步API调用?

This is a special case of this renowned problem . 这是这个著名问题的特例。 Synchronous code can be transformed to asynchronous but not vice versa. 同步代码可以转换为异步代码,反之亦然。

As shown in this similar answer , promises should be used up to application entry point if needed: 这个类似的答案所示,如有需要,应在应用程序入口点使用promise:

module.exports = (async () => {
  const globalSettings = await getEntries({
    content_type: 'globalSettings',
  });

  return routes
  .add('caseStudies', `/${globalSettings.fields.caseStudiesSlug}`, 'caseStudies')
  .add('caseStudy', `/${globalSettings.fields.caseStudiesSlug]}/:slug`, 'caseStudy')
  .add('home', `/`, 'index')
  .add('page', `/:slug*`, 'page'));
})();

This module also exports a promise so it needs to be chained in a module that depends on it. 此模块还导出一个promise,因此需要将其链接到一个依赖于它的模块中。

There is a proposal for top-level await that is intended to provide syntactic sugar for this recipe. 一个针对顶级await的提议,旨在为此配方提供语法糖。

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

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