Promise on JS How to Abort/Cancel an Ongoing

Asked

Viewed 239 times

0

I have an async function saved within a const, I would like to finish it after a while

example:

const p = async () => {
   await Model.create();

  return;
}

const promise = p();

console.log(promise); // Promise { <pending> }


setTimeout(() => {
  // Finalizar o promise agora
}, 100)

Someone knows how I do this, I would like to try to do this without changing the "p"

  • 1

    You say cancel because the create method hasn’t returned yet?

2 answers

1

1

As already mentioned in other answers, there is really no possibility to cancel promises in Javascript. After all, as its name says, it is a promise, therefore, at all times there must be a resolution - whether resolved or rejected.

You have a few options. One of them is to turn to third-party libraries, like Bluebird, which offers this feature, although it comes off by default. Learn more at documentation.

Another option is to simply do nothing at the resolution of the promise. Something like this:

function getPromise(value) {
  return new Promise((resolve) => {
    setTimeout(() => resolve(value), 1000);
  });
}

let cancel = true;

// Exemplo que será cancelado:
getPromise('Exemplo 1').then((resolvedValue) => {
  if (cancel) {
    return; // Não faça nada se tiver sido "cancelada":
  }
  
  console.log('Valor resolvido:', resolvedValue);
});

// Exemplo que NÃO será cancelado:
getPromise('Exemplo 2').then((resolvedValue) => {
  console.log('Valor resolvido:', resolvedValue);
});

Another option is to use the method Promise.race, that solves the value of the first provided promise to be resolved. Thus, you can implement a type of "timeout". If a given promise takes too long to be resolved, a second will be resolved.

function getPromise(value, timeout) {
  return new Promise((resolve) => {
    setTimeout(() => resolve(value), timeout);
  });
}

// Neste exemplo, o timeout será resolvido.
const exampleOnePromise = getPromise('Exemplo 1', 1500);
Promise.race([
  exampleOnePromise,
  getPromise('TIMEOUT do exemplo 1', 1000) // <-- Timeout
])
  .then((resolved) => console.log(resolved));
  
// Neste exemplo, o timeout não será resolvido,
// já que a promessa que queremos foi resolvida antes.
const exampleTwoPromise = getPromise('Exemplo 2', 1001);
Promise.race([
  exampleTwoPromise,
  getPromise('TIMEOUT do exemplo 2', 1501) // <-- Timeout
])
  .then((resolved) => console.log(resolved));

As you can see, in the first example of the above, the "timeout" was resolved, since the promise we passed was too long. In the second, on the other hand, the example promise was resolved before.

There’s nothing very special there. The timeout and the "promise we have tested" are Promises, we are just simulating a behavior of timeout.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.