js promise-如果条件满足,如何结束“然后”执行,如果不满足则继续下一步

我有一个用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,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?工作...

stpab 回答:js promise-如果条件满足,如何结束“然后”执行,如果不满足则继续下一步

您可以通过返回被拒绝的承诺来“停止” struct node { int data; struct node* left; struct node* right; }; //function that initialeze a new node struct node* newNode(int data) { struct node *node = (struct node *) malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return node; } struct node* arrayToBST(int arr[],int start,int end) { int mid = (start + end) / 2; struct node *root = newNode(arr[mid]); root->left = arrayToBST(arr,start,mid - 1); root->right = arrayToBST(arr,mid + 1); return root; } 链,这就是为什么它将“跳转”到then阶段的原因。

catch

本文链接:https://www.f2er.com/3013909.html

大家都在问