My application is built on Nodejs + Mongodb + amqp. The core module is receiving the the message from amqp, then wrap it into the corresponding message transaction. In the message transaction, save the message information into mongodb and some other logic.
function messageReceiverCallback(msg) {
try {
messageHandler(decode(msg));
} catch (ex) {
}
}
function messageHandler(msg) {
function defaultTransaction() {
}
var dispatch = {
'default': defaultTransaction
}
dispatch[MSG.TYPE1] = Msg1Transaction;
// other message transaction here
return (dispatch[msg.type] || dispatch['default'])(msg);
}
function Msg1Transaction(msg) {
// some mongodb operation here...
}
However, when there are several same type messages with different message field value in the queue of amqp, then the messageReceiverCallback will be called, and the Msg1Transaction also be invoked multiple times. As a result, the data saved in the mongodb will be incorrect, because of the asynchronous operation on mongodb which I have ignored. How can I handle it in this case??
I have one idea, add one new transaction queue wrapped with Promise maybe. So the transaction can be processed asynchronously. But I do not how to implement it? could one can help me or some other better solution to solve it?