What is the difference between then and finally in a promise?

后端 未结 3 1442
故里飘歌
故里飘歌 2021-01-01 19:14

I see the docs for Bluebird\'s finally but I still don\'t quite understand the difference vs. then.

To be clear: I know exactly why then ge

3条回答
  •  迷失自我
    2021-01-01 19:37

    All right, after some chatting and a lot of help from KevinB, I figured out at least one difference. Consider the following two new tests:

    function test5 () {
        console.log("REJECT + THEN + CATCH/THROW + THEN");
        return new Promise((resolve, reject) => reject(new Error("rejected")))
           .then(() => console.log("then"))
           .catch(function(err) { throw new Error("error in catch"); })
           .then(() => console.log("end"));
    }
    
    function test6 () {
        console.log("REJECT + THEN + CATCH/THROW + FINALLY");
        return new Promise((resolve, reject) => reject(new Error("rejected")))
           .then(() => console.log("then"))
           .catch(function(err) { throw new Error("error in catch"); })
           .finally(() => console.log("end"));
    }
    

    In these the promise is rejected, but an error is thrown from catch.

    The promise ends up ultimately rejected in both cases but for the finally case the finally is still executed, the then is not.

    So that's the difference. They're almost the same with the sole exception that when an error is thrown from the catch handler, finally executes, and then does not.

    This means the comment I quoted also does have merit: If in my error handler another error occurred, a then wouldn't guarantee clean-up, but a finally would. That's the case I was missing.

提交回复
热议问题