Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

208
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda