它是 TypeScript,使用 BlueBird 和 amqplib。我在某处读到只有失败者使用“延迟”,我不想成为失败者(至少出于这个原因)。所以我开始尝试重写这个没有 - 无济于事(只是还没有):
public Request<Rq extends IPublishable, Rs extends IPublishable>(request: Rq): { ackd: Promise<boolean>; response: Promise<Rs> } {
var ackdPromise: Promise<boolean>;
var responsePromise: Promise<Rs>;
var confirmPublish = Promise.promisify(this.ConfirmChannel.publish, this.ConfirmChannel);
var consumerTag = uuid.v4();
var responseQueue = Bus.rpcQueueBase + consumerTag;
var responseDeferred = Promise.defer<Rs>();
var handleResponse = (msg: IPublishedObj): void => {
//ack first
this.ConfirmChannel.ack(msg);
this.ConfirmChannel.cancel(consumerTag);
responseDeferred.resolve(Bus.FromSubscription(msg));
}
responsePromise = responseDeferred.promise;
ackdPromise = Promise.resolve(this.ConfirmChannel.assertQueue(responseQueue, { durable: false, exclusive: true, autoDelete: true }))
.then((okQueueReply) => Promise.resolve(this.ConfirmChannel.consume(responseQueue, handleResponse, { consumerTag: consumerTag })))
.then((okSubscribeReply) => Promise.resolve(this.ConfirmChannel.assertExchange(Bus.rpcExchange, 'direct', { durable: true, autoDelete: false })))
.then((okExchangeReply) => confirmPublish(Bus.rpcExchange, request.GetType(), Bus.ToBuffer(request), { type: request.GetType(), replyTo: responseQueue }))
.then(this.handleAck, this.handleNack)
.catch((failReason) => {
console.error(util.format('Error publishing: %s', failReason));
return false;
});
return { ackd: ackdPromise, response: responsePromise };
}
我已经转换了所有类似的方法并在此进行了一些运行,但总是不够用。也许是因为我正在尝试返回两个值(确认承诺和响应承诺),但实际上我认为这与尝试为调用嵌入式处理程序的最终结果返回承诺有关 - 不使用延迟。
你能(请)做得更好(或告诉我推迟是可以的)吗?