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

同一处理器添加多个任务无法正常执行问题求助

问题分析与解决方案

你的代码里所有任务只执行一个(或效果一致)的核心原因是对象引用共享:
data是同一个对象实例,循环中每次修改data.recipient时,都是在修改同一个内存地址的内容。而队列保存的是对象引用,不是独立副本。等循环结束后,所有任务的data.recipient都会被覆盖成最后一个循环值,导致执行时看起来只有最后一个任务生效。

解决办法

直接在循环内创建独立的对象副本,确保每个任务拿到的参数都是独立的:

浅拷贝方案(适用于无嵌套对象的data)

const recipients = ['9988998899', '6677887766'];
for (const recipient of recipients) {
    // 基于原data创建新对象,替换recipient属性
    const taskData = { ...data, recipient };
    const job = await this.bsQueue.add('send-push', taskData);
    this.logger.debug(`Job whatsapp push with id: ${job.id} added!`);
}

深拷贝方案(适用于有嵌套对象的data)

如果data包含嵌套对象,浅拷贝无法复制嵌套层级的内容,需要用深拷贝:

const recipients = ['9988998899', '6677887766'];
for (const recipient of recipients) {
    // 通过JSON序列化反序列化生成深拷贝
    const taskData = JSON.parse(JSON.stringify(data));
    taskData.recipient = recipient;
    const job = await this.bsQueue.add('send-push', taskData);
    this.logger.debug(`Job whatsapp push with id: ${job.id} added!`);
}

修改后每个任务会持有独立的参数对象,recipient不会被后续循环覆盖,所有添加的任务都会按预期执行不同的收件人逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 14:20:26