【问题标题】:How to use module.exports to export async function如何使用 module.exports 导出异步函数
【发布时间】:2019-07-30 01:37:37
【问题描述】:

我无法将异步函数的结果返回到我正在调用的路由。我怎样才能成功地做到这一点?

我正在尝试从文件 token_generator.js 中导出一个令牌,并使用 Express 在路由 ('/') 上显示它。我从其他文件导入函数。

const tokenGenerator = require('./src/token_generator'); 

我有一个简单的路线来调用该函数输出。

app.get('/', async function (request, response) {
  const identity = request.query.identity || 'identity';
  const room = request.query.room;
  response.send(tokenGenerator(identity, room));
});

在我的 token_generator 中,我使用 async/await 来检索和生成令牌。我在导出之前记录它,它出现在我的控制台中,但从未进入网页。

async function tokenGenerator(identity, room) {

  const token = new AccessToken(
    process.env.TWILIO_ACCOUNT_SID,
    process.env.TWILIO_API_KEY,
    process.env.TWILIO_API_SECRET
  );

  let grant = new VideoGrant();
  token.identity = Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 8);
  grant.room = await getRoomId(room);
  token.addGrant(grant);
  console.log(token.toJwt());
  return await token.toJwt();
}

module.exports = tokenGenerator;

如何让令牌显示在网页上?我之前有一个工作版本,代码非常相似——但我想使用 async/await 作为比我以前的代码更好的实践。我想必须有不同的方式来调用 Express 中的函数?谢谢

【问题讨论】:

    标签: javascript express async-await


    【解决方案1】:
    app.get('/', async function (request, response) {
      const identity = request.query.identity || 'identity';
      const room = request.query.room;
      // Since your tokenGenerator is async, you need await to get its result
      response.send(await tokenGenerator(identity, room));
    });
    

    【讨论】:

    • 哈哈——工作,很简单。谢谢豪。如果允许,我会在 5 分钟内更新答案。
    猜你喜欢
    • 2019-11-15
    • 2019-07-13
    • 2023-03-10
    • 1970-01-01
    • 2020-01-15
    • 1970-01-01
    • 2020-09-05
    • 2019-11-27
    • 1970-01-01
    相关资源
    最近更新 更多