js promise - 如果满足条件如何结束 "then" 执行,如果不满足则继续下一步

js promise - how to end "then" execution if a condition is fulfilled and continue to next then if not

我有 1 个 .then() 方法的承诺,我想将其分成更小的部分(因为它太长...)。

它看起来类似于这个(简化的)示例:

const myPromise = new Promise((resolve, reject) => {
  setTimeout(function() {
    resolve(false);
  }, 500);
});

myPromise
  .then(value => {
    if (value) {
      // do something
      console.log('value: ' + value)
      console.log('do something');
    } else {
      // do something else only if value=true
      // this is really long.............
      console.log('value: ' + value)
      console.log('do something else');
    }
  });

为了简化我想做这样的事情:

const myPromise = new Promise((resolve, reject) => {
  setTimeout(function() {
    resolve(false);
  }, 500);
});

myPromise
  .then(value => {
    if (value) {
      // do something
      console.log('value: ' + value)
      console.log('do something');
      // stop "then" execution (next "then" should not run) -> HOW TO DO THIS?
    } else {
      // continue processing in next then
      return value
    }
  })
  .then(value => {
    // do something else only if value=false
    console.log('value: ' + value)
    console.log('do something else');
  })

我想不通的是如何让 // stop "then" execution (next "then" should not run) -> HOW TO DO THIS? 工作...

您可以通过返回 rejected 承诺来 "stop" then 链接,这就是为什么它将 "jump" 到 catch 阶段.

const myPromise = new Promise((resolve, reject) => {
  setTimeout(function() {
    resolve(true);
  }, 500);
});

myPromise
  .then(value => {
    if (value) {
      // do something
      console.log('value: ' + value);
      console.log('do something');
      // stop "then" execution (next "then" should not run) -> HOW TO DO THIS?
      return Promise.reject();
    } else {
      // continue processing in next then
      return value;
    }
  })
  .then(value => {
    // do something else only if value=false
    console.log('value: ' + value);
    console.log('do something else');
  });