Search code examples
javascriptnode.jsasync-awaitpromisecancellation

Terminate promise given a socket disconnects


I have an Express.js website that utilizes socket.io. For each user (socket) that connects, a function is called that can take a long time to resolve.

server.js

const app = express();
const server = http.createServer(app);
const io = new Server(server);

io.on('connection', async (socket) => {
  console.log(`${socket.id}: socket connected`);

  console.log(`${socket.id}: computation started`);
  await longRunningTask();
  console.log(`${socket.id}: computation completed`);


  socket.on('disconnect', () => {
    console.log(`${socket.id}: socket disconnected`);

    // TODO: Check if `longRunningTask` has resolved. If it has not, cancel it
  });
});

This is the current flow of the program given a user disconnects before the longRunningTask resolves:

User visits website (they are assigned socket.id tCzH)

tCzH: socket connected
tCzH: computation started

User disconnects

tCzH: socket disconnected

Some time passes

tCzH: computation completed

My goal is to terminate the longRunningTask immediately given the socket is disconnected. What would be the best approach?


Solution

  • Unfortunately, it is impossible to terminate the execution of a function from outside its' scope in Javascript. Even if you wrap your longRunningTask in a Promise and reject that Promise manually, it will not prevent the rest of its stack from execution.

    Implementation of longRunningTask has to be modified so it is dependent on a global variable that is in the outer scope, and once this variable becomes for example false it should return or break itself from within.