+ 1
how to validate a number using a promise
how do I write a promise to validate a number and it resolve should output "the number that was validated" while it reject should say "we want numbers here" when its is not a valid number. for example, 45 is an actual number; // resolve we want numbers here // reject note: it should also accept a number string and reject NaN
5 Answers
+ 4
function validateNumber(n) {
const promiseANumber1 = new Promise((resolve,reject) => {
if(isNaN(n)) reject(n);
else resolve(n);
});
promiseANumber1.then(v=>{
console.log(`${v} is an actual number`)
}).catch((err) => {
console.log("We want a number here");
});
}
https://code.sololearn.com/czZdLvNzJI4v/?ref=app
+ 2
Please, post your try
+ 2
CalviÕ²
I gave this a try too, and I am wondering, is it better practice to use then + catch to represent the separate branches of execution? I guess it looks cleaner, than passing both paths to 'then'.
https://code.sololearn.com/cZ6WYofRBR97/?ref=app
+ 1
Tibor Santa yes, your way is the usual way to handle promise.
+ 1
Thanks, CalviÕ², and Tibor Santa
You guys are amazing
Here's my solution
version 1 :
https://code.sololearn.com/cppIO81FC1ve
version 2:
https://code.sololearn.com/cQ2PjH0UeERB
version 3:
https://code.sololearn.com/cypKCvDlc1lk