I've encountered a challenge in my current implementation. I'm utilizing queues to invoke a specific function (let's call it function a()) within a loop. The loop triggers the queue, leading to multiple calls of the same function a().
Inside function a(), I'm generating a number based on the totalCountOfSavedDocs + 1. For instance, if the savedOrders are 10, the next one should logically be 1. The generated number is then stored in the database (using mongodb) for the next doc saving.
However, due to the loop and the multiple queue calls, the number generation is not happening sequentially. Consequently, I'm facing an issue where the same number is being assigned to multiple documents.
I'd appreciate any insights or suggestions on how to ensure the sequential generation of numbers despite the loop and multiple queue calls.
Here is the code : This is how queue is called :
for await (let order of orders) {
const msg: ServiceBusMessage = {
body: JSON.stringify({
type: "order-create-single",
data: order,
req: reqObj,
})
};
await sender.sendMessages(msg);
}
IN queue :
public async process(orderObj: IOrderAddRequest, req: any) {
try {
await this.addOrderService.createOrder(req, orderObj);
}
catch (err) {
throw err;
}
}

