Node.js中module.exports导出的异步函数无返回值问题求助
解决异步函数无法返回数据的问题
你的问题核心在于**unpaidList函数没有返回异步操作的Promise**,导致调用它的时候无法获取到then回调里的数据。Mongoose的aggregate方法是异步的,会返回一个Promise,但你的函数没有把这个Promise传递出去,所以调用者拿到的是默认的undefined。
第一步:修改服务函数,返回Promise
我们需要让unpaidList返回Loan.aggregate()生成的Promise,这样调用者就能通过异步方式获取结果。
方法1:保留.then链式调用
const mongoose = require("mongoose"); const Loan = require("../models/loan_model"); function unpaidList() { // 直接返回整个Promise链 return Loan.aggregate([ { $group: { _id: "$ePaidunpaid", data: { $push: "$$ROOT" }, count: { $sum: 1 } } } ]).then(function(data){ console.log(data) // 此处仍可打印数据 return data; // 将数据传递给下一个then }) } module.exports = { unpaidList };
方法2:用async/await简化写法(更推荐)
const mongoose = require("mongoose"); const Loan = require("../models/loan_model"); async function unpaidList() { try { const data = await Loan.aggregate([ { $group: { _id: "$ePaidunpaid", data: { $push: "$$ROOT" }, count: { $sum: 1 } } } ]); console.log(data); return data; } catch (err) { // 可以在这里提前处理错误,或者抛出去让调用者处理 throw err; } } module.exports = { unpaidList };
第二步:在路由中正确调用异步函数
因为unpaidList现在返回的是Promise,所以调用时需要用async/await或者.then()来处理结果:
方式1:使用async/await(更直观)
// 注意这里要解构出unpaidList,或者用unpaidListReq.unpaidList const { unpaidList } = require("../services/unpaidlist"); router.get("/", ensureAuthenticated, async (req, res) => { try { // 等待异步操作完成,拿到结果 const unpaidData = await unpaidList(); // 这里可以把数据传给视图,或者返回JSON res.render("your-view-name", { unpaidData }); // 如果是API接口,用res.json(unpaidData); } catch (error) { // 处理可能出现的错误 console.error("获取未还款列表失败:", error); res.status(500).send("服务器错误,无法获取数据"); } });
方式2:使用.then()链式调用
const { unpaidList } = require("../services/unpaidlist"); router.get("/", ensureAuthenticated, (req, res) => { unpaidList() .then(unpaidData => { res.render("your-view-name", { unpaidData }); }) .catch(error => { console.error("获取未还款列表失败:", error); res.status(500).send("服务器错误,无法获取数据"); }); });
为什么之前的写法不行?
原来的unpaidList函数内部执行了异步操作,但函数本身没有返回任何值。当你调用unpaidList()时,函数会立即返回undefined,而then回调里的return data只是把数据返回给了Promise的内部链,并没有传递给函数的调用者。只有让函数返回整个Promise,调用者才能拿到异步操作的最终结果。
内容的提问来源于stack exchange,提问作者Nikhil Savaliya
相关产品推荐
相关产品推荐

