You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swagger-Node项目中如何在中间件使用async函数?

Can I use async functions as middleware in swagger-node's swagger.yaml configuration?

Absolutely, you can use async/await in your swagger-node controller functions—you just need to handle a couple of edge cases related to promise resolution and error handling. Here's how to make it work:

1. Use async/await directly (for newer swagger-node versions)

Most recent versions of swagger-node (built on swagger-tools) properly handle async functions by resolving the returned promise. You can rewrite your controller like this:

module.exports.getPosition = async function(request, response) {
  const positionId = request.swagger.params.positionId.value;
  try {
    // Await your async model call instead of using .then()
    const positionData = await someModel.getPosition(positionId);
    return response.status(200).json(positionData);
  } catch(error) {
    // Handle errors cleanly with try/catch
    return response.status(500).json({ error: error.message });
  }
}

Your existing swagger.yaml configuration doesn't need any changes—swagger-node will still recognize the getPosition function as long as it's exported correctly and linked via x-swagger-router-controller and operationId.

2. Wrap async functions (for older swagger-node versions)

If you're stuck on an older version that doesn't automatically resolve async function promises, you can wrap your async functions to convert them into standard Express middleware. This ensures uncaught errors are passed to the error-handling pipeline:

First, create a simple wrapper utility:

// utils/wrapAsync.js
const wrapAsync = (fn) => (req, res, next) => {
  // Resolve the async function and pass errors to next()
  Promise.resolve(fn(req, res, next)).catch(next);
};

module.exports = wrapAsync;

Then use it in your controller:

const wrapAsync = require('../utils/wrapAsync');

module.exports.getPosition = wrapAsync(async function(request, response) {
  const positionId = request.swagger.params.positionId.value;
  const positionData = await someModel.getPosition(positionId);
  response.status(200).json(positionData);
});

With this wrapper, any uncaught errors from your async code will be passed to swagger-node's default error handler, preventing hanging requests.

Key Notes

  • Node.js Version: Make sure you're running Node.js 8 or later, as async/await is natively supported from this version onward.
  • Error Handling: Always use try/catch in your async functions or a wrapper like the one above—unhandled promise rejections will crash your app if not caught.
  • No YAML Changes Needed: Your swagger.yaml paths configuration stays exactly as you have it now; the change is only in how you write your controller functions.

内容的提问来源于stack exchange,提问作者Talita

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:09:12