Rethrowing error in promise catch

前端 未结 6 1824
迷失自我
迷失自我 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条回答
  •  猫巷女王i
    2021-01-30 03:32

    There is no important difference if you leave out the catch method call completely.

    The only thing it adds is an extra microtask, which in practice means you'll notice the rejection of the promise later than is the case for a promise that fails without the catch clause.

    The next snippet demonstrates this:

    var p;
    // Case 1: with catch
    p = Promise.reject('my error 1')
           .catch(function(error) {
              throw(error);
           });
    
    p.catch( error => console.log(error) );
    // Case 2: without catch
    p = Promise.reject('my error 2');
    
    p.catch( error => console.log(error) );

    Note how the second rejection is reported before the first. That is about the only difference.

提交回复
热议问题