1

I want to call function from my object in express route. This function should call mongoose query, then run next, next etc. - all needed operations.

Here is my example route:

var MailSender = require('../../libs/mailer');

router.get('/mailer/test', function (req, res, next) {
    MailSender.getPending();
});

And mailer file:

(here include all required)

module.exports = {

    currentMails : {},

    getPending : function() {

        MailObj.find()
            .limit(10)
            .exec(this.blockPending);
    },


    blockPending : function(err, mail) {
        currentMails = {};

        mail.forEach(function(data) {
            let mailId = mongoose.Types.ObjectId(data._id);
            currentMails[mailId] = data;
        });

        MailObj.update({ _id: { $in: Object.keys(currentMails)  } }, { block: 1 }, {multi: true}, function() {
            // Doesn't work
            this.myNextFunc();
        });
    },



    myNextFunc : function() {
      console.log("Yep!");
    }
}
  • getPending - it works great and call blackPending with query results.
  • blockPending - works greats, I can prepare ids and update records

But... myNextFunc() doesn't work and I can't call any object function from this scope (console says that they are undefined). I know, that I make something wrong but... what?

I'ld like to encapsule related functions in such objects and run inside as callbacks. What am I doing wrong?

6
  • try adding a callback to getPending. Commented Dec 5, 2017 at 15:42
  • @DakshMiglani but it should be called after blockPending (after update records on database) Commented Dec 5, 2017 at 15:43
  • see, till the time block pending completes the query express has returned the function and send the status of 200. so what you can do is send the 200 status after your query has done. Commented Dec 5, 2017 at 15:46
  • try using promises with async and await. Commented Dec 5, 2017 at 15:47
  • 1
    so use promises instead of callbacks and use async await with it. Commented Dec 5, 2017 at 15:56

1 Answer 1

0

As far as you are using Mongoose, why don't you take profit of it, and you update each mail in the loop?? It is less efficient, but maybe as a first approach it deserves:

var numUpdates = 0;
mail.forEach(function(data) {
    data.block = 1;
    data.save(function(err, mailSaved) {
        //check error
        if(numUpdates ++ >= mail.length) {
            this.myNextFunc();
        }
    })
});
Sign up to request clarification or add additional context in comments.

1 Comment

I'd like to first block all mails using this flag and then send them using other method and external API. I can set flag and also send inside loop, but script should be called from cron and should mark all mails to send as block as soon as it possible to avoid conflict with other cron calls.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.