Created
January 8, 2023 15:35
-
-
Save geekyorion/2c44db81a7a923704fd4d4fd238022ba to your computer and use it in GitHub Desktop.
Revisions
-
geekyorion created this gist
Jan 8, 2023 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,49 @@ // think of this as a DB const users = [ { username: "name1234", password: "password" }, { username: "user1234", password: "pass" } ]; // username and password of the user const username = "name1234"; const password = "password"; // function to print if user is found or not const printResult = result => { console.log(`user is ${result ? "" : "not "}found`); } // using a flag let found = false; users.forEach(user => { // since you can not use break or continue in the forEach loop, use return to complete the current callback execution by returing it if (found) return; if (user.username === username && user.password === password) { found = true; } }); printResult(found); // user is found; // create promise to check the username and password const checkForUser = (_username, _password) => new Promise((resolve, reject) => { try { users.forEach(user => { if (user.username === _username && user.password === _password) { resolve(true); } }); resolve(false); } catch { // in case it is actual DB and it is failed to process the query reject("Unable to check user details"); } }); checkForUser(username, password) .then(result => printResult(result)) // user is found .catch(err => console.log(err)); checkForUser("geekyorion", "dummyPass") .then(result => printResult(result)) // user is not found .catch(err => console.log(err));