1

I have the following codes:

function promise3() {
    return new Promise((resolve, reject) => {
        function1().then(() => {
            resolve();
        }).catch(err => {
            reject(err);
            console.log("after error");
        });  
    })
} 

promise3().catch(e => {
    console.log(e);
});

function1 returns a promise. But when function1 fails and returns an error. I see the console.log("after error") before the console.log of the error. I though the codes after reject would not run. reject acts like a return. What is happening here then?

Yugue Chen
  • 79
  • 5
  • 3
    Of course? `reject()` is just a function call, it doesn't do anything beyond that. If you want code execution to end when you trigger resolve or reject, `return` them, to terminate the promise function immediately. – Mike 'Pomax' Kamermans Aug 04 '20 at 23:23
  • Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi Aug 05 '20 at 01:11

1 Answers1

-1

If you don't want to execute anything after resolve/reject you need to return them as follow.

 function promise3() {
        return new Promise((resolve, reject) => {
            function1().then(() => (
                resolve(); //change the brackets to () instead of {}
            )).catch(err => {
                return reject(err); //put a return keyword in front
                console.log("after error");
            });  
        })
    } 
    
    
    promise3().catch(e => {
        console.log(e);
    });
   

(): mean that you are returning that is inside.
{}: mean that you need to do the following tasks and return nothing if there is no return statement.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
KDSG
  • 145
  • 1
  • 6