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

Node.js跨文件嵌套函数调用报错:TypeError: quotes_5 is not a constructor

Node.js模块导入导出错误:TypeError: quotes_5 is not a constructor

问题场景

拆分Node.js代码到多个文件后,调用quotes_5函数时触发错误:TypeError: quotes_5 is not a constructor,核心原因是误用new关键字调用普通函数,同时存在模块导入后的调用错误。

错误分析与修复步骤

1. 错误:用new调用普通异步函数

quotes_5.js导出的是一个普通异步函数,不是类或构造函数,不能用new关键字实例化。

修复main.js中的调用:

const quotes_uni_v2 = require("./quoter_uni_v2");
const quotes_5 = require("./quotes_5");
async function calc(route) {
  // 去掉new关键字,直接调用异步函数
  amountOut = await quotes_5(
    quickswap_router,
    sushiswap_router,
    route,
    amount_wei
  );
  return amountOut;
};

2. 错误:导入模块后错误访问函数

quoter_uni_v2.js直接导出了quotes_uni_v2函数,require后得到的就是函数本身,无需通过.quotes_uni_v2属性访问。同时注意文件名拼写:原文件名为quoter_uni_v2.js,quotes_5.js中require的路径需要匹配。

修复quotes_5.js中的调用:

// 修正文件名路径为quoter_uni_v2.js
var quotes_uni_v2 = require("./quoter_uni_v2");

module.exports = async function (router1, router2, route, amount_wei) {
  console.log(route);
  // 直接调用导入的函数,去掉.quotes_uni_v2
  var amount_Out = await quotes_uni_v2(
    route[1],
    route[2],
    amount_wei,
    router1
  );
  // ... 其他业务代码
  return (
    Math.round(ethers.utils.formatEther(amount_Out[1].toString()) * 100) / 100
  );
};

3. 额外检查:确保quoter_uni_v2函数支持异步调用

如果router.getAmountsOut是异步方法,需要将quoter_uni_v2改为异步函数:

// quoter_uni_v2.js修改为异步函数
module.exports = async function quotes_uni_v2(tokenIn, tokenOut, amountIn, router) {
  const quotedAmountOut = await router.getAmountsOut(amountIn.toString(), [
    tokenIn,
    tokenOut,
  ]);
  return quotedAmountOut;
};

总结

  • 普通函数(包括异步函数)不能用new关键字调用,直接以函数名(参数)形式调用即可。
  • 模块导出单个函数时,require后直接得到该函数,无需额外属性访问。
  • 确保文件名和require路径完全匹配,避免拼写错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 07:03:34