Rethrowing error in promise catch

前端 未结 6 1764
迷失自我
迷失自我 2021-01-30 02:59

I found the following code in a tutorial:

promise.then(function(result){
    //some code
}).catch(function(error) {
    throw(error);
});

I\'m

6条回答
  •  北恋
    北恋 (楼主)
    2021-01-30 03:37

    In the promise chain, it is better to use .catch

    ex in function f2: .then(...).catch(e => reject(e));

    • test1 - with try catch
    • test2 - without try or .catch
    • test3 - with .catch

    function f1() {
        return new Promise((resolve, reject) => {
            throw new Error('test');
        });
    }
    
    function f2() {
        return new Promise((resolve, reject) => {
            f1().then(value => {
                console.log('f1 ok ???');
            }).catch(e => reject(e));
        });
    }
    
    function test1() {
        console.log('test1 - with try catch - look in F12');
        try {
          f2().then(() => { // Uncaught (in promise) Error: test
            console.log('???'); });
        } catch (e) {
          console.log('this error dont catched');
        }
    }
    
    function test2() {
        console.log('test2 - without try or .catch - look in F12');
        f2(); // Uncaught (in promise) Error: test
    }
    
    function test3() {
      console.log('test3 - with .catch');
      f2().then(value => {
        console.log('??');
      }).catch(e => {
        console.log(' now its ok, error ', e);
      })
    }
    
    setTimeout(() => { test1(); 
      setTimeout(() => { test2(); 
        setTimeout(() => { test3(); 
        }, 100);
      }, 100);
    }, 100);

提交回复
热议问题