3

My node code starts the running of an async function inside the routes.js file.

This is an absolutely critical function, but what happens when a user closes the tab of my application? When a user closes the session, i would like to be able to stop the execution of the async function.

I search in the github forums but i found this is not possible.

The closest i managed to find is this post: How can I abort an async-await function after a certain time?

But the abortion of the function happens after a certain time here, and not wether or not the user has closed my page. So is it possible to do something similar for my programming need?

EDIT: The structure of my code is this:

//resource_file.js
module.exports = async function doStuff(arg) {
....
}

//--------------------------------------------------------------------

//routes.js
let funker = require('./resource_file.js');

module.exports = function(app) {
    app.post('/pst', function(req, res) {
            var arg = req.body.convo;
            funker(arg).then(result => {
                res.render('index.ejs');
            }).catch(err => {
                console.log(err);
                res.render('index.ejs');
            })
    });
....
}
user1584421
  • 3,499
  • 11
  • 46
  • 86
  • It would help to see your code. The first thing that comes to mind is to detect the tab close and set some flag. When the async thing executes, it sees the flag and aborts (re: returns out). – pushkin Aug 09 '18 at 16:28
  • What exactly is your route code doing? And no, the server does usually not get notified when the user closes his browser (tab) - a ping (or websocket) with a timeout is the best you can do. – Bergi Aug 09 '18 at 16:31
  • You'd just write something like `async function() { await a(); if (shouldStop) return; await b(); }` – Bergi Aug 09 '18 at 16:33
  • You need to get notified when the browser is closed: [Best way to detect when a user leaves a web page?](https://stackoverflow.com/q/147636) – Heretic Monkey Aug 09 '18 at 16:33
  • but how do i pass the function the flag when the function is already running? – user1584421 Aug 09 '18 at 19:20
  • @user1584421 Already running or already queued up to run? You don't pass it the flag, you set some flag (like a global, for instance) and reference it from your function – pushkin Aug 10 '18 at 13:06
  • @pushkin it is already running – user1584421 Aug 10 '18 at 15:07
  • @user1584421 It would help to see what your async function looks like. – pushkin Aug 10 '18 at 15:09
  • @pushkin I just edited the question. Thanks! – user1584421 Aug 10 '18 at 15:31

0 Answers0