Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute function after return

I'm using nodejs with expressjs for my api.

I want to call a function after res.json() is called.

for example the api fetches data to the client but i want to log that action but no need to make client wait for request response till the api saves log

module.exports = {
  getAll:async function(req,res){
    ////fetch data from db
    res.json({success:true,data:data});
    module.exports.logthis();
    return;
  },
  logthis: async function ()
  {
    //save log
  }
}

is this true that logthis will not be interupted after return; is called ? also is there a better pattern to do this, like a event queue listener so that i threw that request in a pool and it's executed whenever it's possible ?

like image 511
JenuRudan Avatar asked Nov 27 '25 19:11

JenuRudan


1 Answers

Sending a json response to the client or using return statement will not stop the script from executing logthis function only if you put return statement before it.

module.exports = {

    getAll:async function(req,res){

        //fetch data from db

        res.json({success:true,data:data});

        this.logthis(data);

        return;
    },

    logthis: function (data) {
        // log data to file here
    }

}

Remember that async function works in conjunction with await statement, if you don't have asynchronous functions inside getAll there is no need to use async keyword

like image 200
YouneL Avatar answered Nov 30 '25 08:11

YouneL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!