Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

214
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda