Lakshmi
Lakshmi

Reputation: 338

setTimeout() in Node.js

I am writing cloud functions on Cloud Firestore triggers. What I want is when a document is added under some uuid it has to deleted after 2 minutes and assign the same data to another document. I wrote some code regarding that like below

exports.createdOpenOrder = functions.firestore.document('Some/{psId}/Open/{OrderId}').onCreate((snap, context) => {
    // Get an object representing the document
    console.log("Deleting function execution started:");

    const newValue = snap.data();
    var OrderId = context.params.OrderId;
    var psId = context.params.psId;

    setTimeout(delete_cur, 120000);

    function delete_cur() {

        var data = db.collection('Some').doc(psId).collection('Open').doc(OrderId).delete().then(function() {
            console.log("Document successfully deleted!");
            // calling another function to reassign
            reassign(OrderId);
            return;
        }).catch(function(error) {
            console.error("Error removing document: ", error);
            return;
        });

     }

});

Now my problem is the setTimeout function is not calling exactly after 2 minutes and data is not deleting. Is anything wrong with my code? Please let me know how to write code work perfectly on setTimeout.

Upvotes: 0

Views: 322

Answers (1)

Steven Spungin
Steven Spungin

Reputation: 29179

To find the problem, put log before, and a catch around, the contents of your setTimeout handler.

Currently you are only trapping exceptions after the delete async function returns. All other exceptions in the chain, before calling delete, are not caught.

function delete_cur() {
  console.log('handler called')
  try {
    var data = db.collection('Some').doc(psId).collection('Open').doc(OrderId).delete().then(function() {
      console.log("Document successfully deleted!");
      // calling another function to reassign
      reassign(OrderId);
      return;
    }).catch(function(error) {
      console.error("Error removing document: ", error);
      return;
    });
  } catch (e) {
    console.error('could not invoke delete', e)
  }

}

Upvotes: 1

Related Questions