-1

I am relatively new to javascript and want to find out how the things here work. I don't understand why does it output testing.js:2 Uncaught (in promise) Oops instead of catching this error and handling it. Everything works fine if I just type reject(..) Here is the code:

let alex = new Promise((resolve,reject)=>{
    return Promise.reject('Oops');
})
.then((r)=>console.log(r))
.catch((err)=>console.log(err));
Alexey_js
  • 77
  • 5
  • 2
    `return Promise.reject(...)` creates a new rejected promise. You do not handle the error on that promise. Returning a promise in a promise constructor does not make the constructed promise chain off of the returned one. As you point out, the correct way to do this is to use `reject("Oops")` instead. – CRice Apr 30 '20 at 18:46

1 Answers1

4

That's because you should use the two arguments received in the callback (resolve and reject). As you said, it works when you use reject('Oops') instead of return Promise.reject('Oops'). It should look like this:

let alex = new Promise((resolve,reject)=>{
    reject('Oops');
})
.then((r)=>console.log(r))
.catch((err)=>console.log(err));

You can read more about promises here

Alejandro De Cicco
  • 1,216
  • 3
  • 17