这个catch块会执行吗?

时间:2018-09-06 04:28:58

标签: javascript

那么我们有可能进入第二个错误块吗? 鉴于我们在逻辑部分中有些许诺拒绝或发生错误

somePromise
  .then(function(data) {
      //some logic
      return something;
    })
    .then((data) => {
      // more logic
    }, function(err) {
      // first error block
    })
    .catch(function(err) {
      // second error block
    });

3 个答案:

答案 0 :(得分:2)

是的,有可能-如果传递给.then的第二个函数抛出错误(或返回拒绝的Promise),则错误将被传递到下一个.catch

Promise.resolve()
  .then(function(data) {
      //some logic
      throw new Error();
    })
    .then((data) => {
      // more logic
    }, function(err) {
      // first error block
      console.log('Handling first error');
      return err.somePropertyThatDoesNotExist.text;
    })
    .catch(function(err) {
      // second error block
      console.log('Handling second error')
    });

如注释所述,如果传递给第二个catch first 函数抛出错误,则.then也将运行:

Promise.resolve()
  .then(function(data) {
      //some logic
      return 'Foo';
    })
    .then((data) => {
      // more logic
      throw new Error();
    }, function(err) {
      // first error block
      console.log('Handling error in then');
    })
    .catch(function(err) {
      // second error block
      console.log('Handling error in catch')
    });

答案 1 :(得分:0)

是的,如果#include<stdio.h> int main() { int cost[10][10], path[10][10], distance[10]; int i, j, n, visit_node, paths, row, column, min, Index; printf("Enter number of nodes!\n"); scanf("%d", &n); printf("Enter cost matrix!\n"); for(i=1; i<=n; i++) { for(j=1; j<=n; j++) { scanf("%d", &cost[i][j]); } } //reading path matrix printf("\nEnter the node you want to visit: "); scanf("%d", &visit_node); printf("\nEnter paths for entered node: "); scanf("%d", &paths); printf("\nEnter path matrix"); for(i=1; i<=paths; i++) { for(j=1; j<=n; j++) { scanf("%d",&path[i][j]); } } for(i=1; i<=paths; i++) { distance[i] = 0; row = 1; for(j<1; j<=n; j++) { if(row!=visit_node) { column = path[i][j+1]; distance[i] = distance[i] + cost[row][column]; } row = column; } } min = distance[1]; for(i=1; i<=paths; i++) { if(distance[i]<=min) { min = distance[i]; Index = i; } } printf("\nThe minimum distance value of %d", min); printf("\nminimum distance path is: "); for(i=1; i<=paths; i++) { if((path[Index][i])!=0) { printf("%d---->", path[Index][i]); } } } .catch块中发生错误,将调用// more logic的回调。

// first error block不会因// first error block中发生的错误而被调用

答案 2 :(得分:0)

是的,它将在第一个块中捕获错误,这里是下面的示例。

var promise1 = new Promise(function(resolve, reject) {
  throw 'Ohh Nooo!';
});

promise1.then((data) => {
  // more logic
}, function(err) {
  // first error block
  console.log("Catch Error Block 1");
}).catch(function(error) {
  console.log(error);
});
// expected output: Uh-oh!