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
相关产品推荐
相关产品推荐

