+ 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

8th Jul 2022, 10:46 PM
Chinedu Gabriel
Chinedu Gabriel - avatar
5 Respostas
+ 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
9th Jul 2022, 6:58 AM
Calviղ
Calviղ - avatar
+ 2
Please, post your try
9th Jul 2022, 3:30 AM
KrOW
KrOW - avatar
+ 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
9th Jul 2022, 8:14 AM
Tibor Santa
Tibor Santa - avatar
+ 1
Tibor Santa yes, your way is the usual way to handle promise.
9th Jul 2022, 9:43 AM
Calviղ
Calviղ - avatar
+ 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
10th Jul 2022, 3:08 AM
Chinedu Gabriel
Chinedu Gabriel - avatar