最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

ecmascript 6 - Cancel JavaScript Promise - Stack Overflow

matteradmin4PV0评论

I am trying to cancel a promise as given below:

function example(cancel = Promise.reject()) {
    return new Promise((resolve, reject) => {
        const timer = setTimeout(() => resolve('jack-jack'), 5000);
        cancel.then((res) => {
            clearTimeout(timer);
            reject('cancelled'); 
        }, ()=>{})
    });
}
var cancel=Promise.reject(); 
example(cancel).then((res) => console.log('res handled:' + res)).catch((err) => console.log('err handled:' + err));
console.log('attempting cancellation of promise');
cancel=Promise.resolve();

However I am not able to cancel it. What am I doing wrong over here?

I am trying to cancel a promise as given below:

function example(cancel = Promise.reject()) {
    return new Promise((resolve, reject) => {
        const timer = setTimeout(() => resolve('jack-jack'), 5000);
        cancel.then((res) => {
            clearTimeout(timer);
            reject('cancelled'); 
        }, ()=>{})
    });
}
var cancel=Promise.reject(); 
example(cancel).then((res) => console.log('res handled:' + res)).catch((err) => console.log('err handled:' + err));
console.log('attempting cancellation of promise');
cancel=Promise.resolve();

However I am not able to cancel it. What am I doing wrong over here?

Share Improve this question edited Jul 2, 2018 at 13:51 user7637745 9852 gold badges14 silver badges27 bronze badges asked Jul 2, 2018 at 13:49 useruser 5686 silver badges19 bronze badges 2
  • If cancel is rejected, cancel.then() is not executed. – axiac Commented Jul 2, 2018 at 14:01
  • @BenjaminGruenbaum has an answer with other ways to cancel things at stackoverflow./questions/30233302/…, though I don’t think it’s a duplicate. – Ry- Commented Jul 2, 2018 at 14:07
Add a ment  | 

4 Answers 4

Reset to default 1

In your code you pass already a plete (rejected) Promise to the function. And cancel=Promise.resolve(); after attempting cancellation of promise won't have any effect to promise that was passed to example because you just create a new resolved Promise.

If you want to cancel a running process then you might want choose such a solution:

function example(helper) {
  return new Promise((resolve, reject) => {
    helper.cancel = function() {
      clearTimeout(timer)
      reject('cancelled');
    }
    const timer = setTimeout(() => resolve('jack-jack'), 5000);

  });
}
var helper = {};
example(helper).then((res) => console.log('res handled:' + res)).catch((err) => console.log('err handled:' + err));

console.log('attempting cancellation of promise');
helper.cancel()

You’ve assigned a rejected promise to a variable, passed the rejected promise into your function, and assigned a resolved promise to the variable. The two values the variable takes on are unrelated, and you can’t change the state of a settled promise.

Pass in a promise you can resolve:

let cancel;
let cancelPromise = new Promise((resolve) => {
    cancel = resolve;
});

example(cancelPromise).then(…).catch(…);
console.log('attempting cancellation of promise');
cancel();

function example(cancel = Promise.reject()) {
    return new Promise((resolve, reject) => {
        const timer = setTimeout(() => resolve('jack-jack'), 5000);
        cancel.then((res) => {
            clearTimeout(timer);
            reject('cancelled'); 
        }, ()=>{})
    });
}

let cancel;
let cancelPromise = new Promise((resolve) => {
    cancel = resolve;
});

example(cancelPromise)
    .then((res) => console.log('res handled:' + res))
    .catch((err) => console.log('err handled:' + err));
console.log('attempting cancellation of promise');
cancel();

Since the cancel is set to reject, the then part

cancel.then((res) => { //you cannot use then for reject, as reject cannot be resolved.
    clearTimeout(timer);
     reject('cancelled'); 
}, ()=>{})

will never gets executed hence you have to resolve it, not reject it

function example(cancel = Promise.reject()) {
    return new Promise((resolve, reject) => {
        const timer = setTimeout(() => resolve('jack-jack'), 5000);
        cancel.then((res) => { //you cannot use then for reject
            clearTimeout(timer);
            reject('cancelled'); 
        }, ()=>{})
    });
}

var cancel = Promise.resolve(); // just change to resolve

example(cancel).then((res) => console.log('res handled:' + res)).catch((err) => console.log('err handled:' + err));

console.log('attempting cancellation of promise');
cancel=Promise.resolve(); // this will have no effect as you have already passed a reject

Because you are passing rejected promise. Pass the resolved promise if you want cancel.then() block to run.

function example(cancel = Promise.resolve()) {
  return new Promise((resolve, reject) => {
    console.log(cancel);
    const timer = setTimeout(() => {
      resolve('jack-jack'), 5000
    });
    cancel.then((res) => {
      console.log('CANCELLED');
      clearTimeout(timer);
      reject('cancelled');
    }, () => {})
  });
}
var cancel = Promise.resolve();
example(cancel).then((res) => console.log('res handled:' + res)).catch((err) => console.log('err handled:' + err));
console.log('attempting cancellation of promise');
cancel = Promise.resolve();

Post a comment

comment list (0)

  1. No comments so far