j obe
j obe

Reputation: 2029

Trying to break down this promise example

I've been learning a bit about promises and I came across this example but can't quite understand how it's working. Would someone be able to help break this down into steps so I can understand please, I'm mostly thrown by the cancel parameter and how it's being used. I've tried running the code in console too but I'm still confused. Thanks.

    const wait = (
  time,
  cancel = Promise.reject()
) => new Promise((resolve, reject) => {
  const timer = setTimeout(resolve, time);
  const noop = () => {};

  cancel.then(() => {
    clearTimeout(timer);
    reject(new Error('Cancelled'));
  }, noop);
});

const shouldCancel = Promise.resolve(); // Yes, cancel
// const shouldCancel = Promise.reject(); // No cancel

wait(2000, shouldCancel).then(
  () => console.log('Hello!'),
  (e) => console.log(e) // [Error: Cancelled]
); 

Upvotes: 0

Views: 30

Answers (1)

Syed H
Syed H

Reputation: 270

To begin with, Promise.resolve() returns a Promise object that is resolved. Similarly, Promise.reject() returns a rejected Promise object.

The cancel variable holds a rejected or resolved Promise object (a rejected Promise by default).

In case the Promise object within cancel is resolved, it will immediately clear out the timer set in the timer variable and reject it's parent Promise. You can see this in the comment on this line:

const shouldCancel = Promise.resolve(); // Yes, cancel

In case the Promise object within cancel is rejected, it will not clear out the timer, since it won't get to run the lines of code where the timer is cleared out and will instead run the noop function which is an empty no operations funciton. Thus it will let the timer follow it's course and finally resolve it's parent Promise. You can see this in the comment on this line:

// const shouldCancel = Promise.reject(); // No cancel

So the timer will follow it's natural course if shouldCancel = Promise.reject() and return a resolved Promise. If shouldCancel = Promise.resolve(), the timer will get cancelled, and the Promise will be rejected.

Upvotes: 1

Related Questions