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

Node.js中如何将异步Sequelize查询结果push到数组中?

问题原因

空数组问题本质是异步执行顺序问题:
Dokterl.findOne() 是异步接口,返回Promise对象,循环中触发的所有查询操作还没完成回调执行l.push(dokterl)的时候,外层的console.log(l)和res.json()就已经执行了,所以此时l还是初始的空数组。

修复后的代码

exports.getdoctorcategorybyid = async (req, res) => {
    try {
        const id = req.params.id;
        const doctorcategoryes = await doctorcategory.findOne({
            where: {
                dokter_category_id: id
            }
        });
        if (!doctorcategoryes) {
            return res.status(200).json({
                error: true,
                response: "not found!",
                data: [],
            });
        }
        const dokter_l = doctorcategoryes.id_doctor.split(', ');
        // 批量执行所有查询,等待全部完成后才会执行后续逻辑
        const l = await Promise.all(
            dokter_l.map(docId => 
                Dokterl.findOne({
                    where: { id_doctor: docId }
                })
            )
        );
        // 这里l已经是填充好的数组了
        console.log(l);
        res.status(200).json({
            error: false,
            response: "List!",
            data: doctorcategoryes,
            doctorList: l // 可直接把查询到的医生列表返回给前端
        });
    } catch (err) {
        // 捕获异步错误,避免服务无响应崩溃
        res.status(500).json({
            error: true,
            response: "server error",
            data: []
        })
    }
};

核心修改点

  • 直接用await替代then链式调用,代码逻辑更直观,异步执行顺序可控
  • 用Promise.all批量执行所有医生ID的查询操作,等待所有异步查询全部完成后才会继续执行后续的打印和响应逻辑,此时l已经是填充完毕的数组
  • 新增try/catch捕获所有异步操作抛出的异常,避免服务端崩溃

如果部分id查询不到返回null,你可以在拿到l之后加过滤逻辑:const validList = l.filter(Boolean) 去除空值。

内容的提问来源于stack exchange,提问作者Kodingan Anak Muda

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 23:45:08