JavaScript Promises

Hi, I’m learning promises in JavaScript, and I was wondering about the regarding code:

const executor = (resolve, reject) => { var num = Math.floor(Math.random() * 10); if (num > 5) resolve(num); else reject(num); } const successHandler = resolvedValue => {console.log(resolvedValue); return new Promise(executor);}; const failureHandler = rejectionReason => {console.log(rejectionReason); return new Promise(executor);}; var prom = new Promise(executor).then(successHandler).catch(failureHandler); console.log(prom.then(successHandler).catch(failureHandler));

Why it outputs only two values when they both are greater than 5, and when they are less than 5, it outputs more than two, and than raises an error? sometimes it only logs three numbers without an error

Could someone help me to understand what is going on here? what’s the cause for these variety outputs?
and thanks.

You put the num inside the reject() call instead of an error. Thus, when the num is greater than 5, your promise correctly resolves and returns the num, which you then console.log(). Unfortunately, when the num is less than 5, your promise also correctly rejects and returns the num, which you then console.log(). The error isn’t built into the reject callback. Reject returns what you tell it to so that you can customize error codes.

1 Like

I will try to have a look at this once I have learnt some more about promises.

1 Like

@mus19pro thanks for coming to the study session today! I am new to javascript promises, but I think the issue is what @taylorsabbag said and you need to add a message in the return value for reject() rather than num.

Also think there are some extra lines of code that aren’t necessary, maybe you added them for testing the code?

Here’s what worked for me:

const executor = (resolve, reject) => { var num = Math.floor(Math.random() * 10); if (num > 5) resolve(num); else reject('Number is not greater than 5'); } const successHandler = resolvedValue => { console.log(resolvedValue); }; const failureHandler = rejectionReason => { console.log(rejectionReason); }; var prom = new Promise(executor) .then(successHandler) .catch(failureHandler); console.log(prom);

Thanks for answering Grace.
I didn’t understand @taylorsabbag answer at the beginning because I was confused, like what does he mean by put num instead of an error? It makes sense now
But what I don’t understand why reject would resolves a number anyway? why it treats number differently from strings? is that always the case?

reject() will just return what you put in the brackets.

So if you have reject(num) it will return the value of num , or it we put in a string it will return that, e.g. reject('Number is not greater than 5')

Often an error is passed to reject() or another promise to run when the error is rejected. There is more detail here:

Hope that helps explain it!