Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

215
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!