0

I want to use Mongoose's bulk operation for upserting transactions. For each of my transactions I want to process them in a loop and within that loop I need to use a promise. After that promise resolved, I want to add the upsert to the bulk.

My problem here is, that although I await for every promise to finish, the bulk is executed at the end of the function before any of the promises is resolved. What am I doing wrong or how can I fix this?

   const bulkTransactions = Transaction.collection.initializeUnorderedBulkOp();

   transactions.forEach( async (transaction: any) => {

        // do some suff, fill transaction_data

        await Utils.processTransactionType(transaction).then((action: any) => {

            if (action) {
                // do other stuff
            }

            bulkTransactions.find({_id: hash}).upsert().replaceOne(transaction_data);

        }).catch((err: Error) => {
            // log error
        });
    });

    await bulkTransactions.execute().catch((err: Error) => {
         // log error
    });
phoebus
  • 1,280
  • 1
  • 16
  • 36

1 Answers1

-1

As far as I know, when using await, you no longer use the then return value:

   const bulkTransactions =    Transaction.collection.initializeUnorderedBulkOp();

   transactions.forEach( async (transaction: any) => {

        // do some suff, fill transaction_data

        let action = await Utils.processTransactionType(transaction);

        if (action) {
            // do other stuff
        }

        bulkTransactions.find({_id: hash}).upsert().replaceOne(transaction_data);


    });

    await bulkTransactions.execute().catch((err: Error) => {
         // log error
    });
user184994
  • 17,791
  • 1
  • 46
  • 52