所以无论我读过什么,即使我做对了,我似乎也无法掌握异步和等待的窍门。例如,我的创业公司就有这个。
启动.js
await CommandBus.GetInstance();
await Consumers.GetInstance();
调试跳转到 CommandBus 的 get 实例的末尾(为 rabbitmq 启动一个通道)并启动 Consumers.GetInstance(),但由于通道为空而失败。 命令总线.js
export default class CommandBus {
private static instance: CommandBus;
private channel: any;
private conn: Connection;
private constructor() {
this.init();
}
private async init() {
//Create connection to rabbitmq
console.log("Starting connection to rabbit.");
this.conn = await connect({
protocol: "amqp",
hostname: settings.RabbitIP,
port: settings.RabbitPort,
username: settings.RabbitUser,
password: settings.RabbitPwd,
vhost: "/"
});
console.log("connecting channel.");
this.channel = await this.conn.createChannel();
}
static async GetInstance(): Promise<CommandBus> {
if (!CommandBus.instance) {
CommandBus.instance = new CommandBus();
}
return CommandBus.instance;
}
public async AddConsumer(queue: Queues) {
await this.channel.assertQueue(queue);
this.channel.consume(queue, msg => {
this.Handle(msg, queue);
});
}
}
消费者.js
export default class Consumers {
private cb: CommandBus;
private static instance: Consumers;
private constructor() {
this.init();
}
private async init() {
this.cb = await CommandBus.GetInstance();
await cb.AddConsumer(Queues.AuthResponseLogin);
}
static async GetInstance(): Promise<Consumers> {
if (!Consumers.instance) {
Consumers.instance = new Consumers();
}
return Consumers.instance;
}
}
抱歉,我意识到这是在 Typescript 中,但我想这并不重要。调用 cb.AddConsumer 时会出现此问题,该命令可在 CommandBus.js 中找到。它尝试针对尚不存在的通道断言队列。看不懂的,在看。我觉得我已经覆盖了所有等待区域,因此它应该等待频道创建。CommandBus 始终作为单例获取。如果这会引起问题,我不会,但它也是我所涵盖的领域之一等待。任何帮助都非常感谢大家。