Skip to content

Instantly share code, notes, and snippets.

@geekyorion
Created January 8, 2023 15:35
Show Gist options
  • Select an option

  • Save geekyorion/2c44db81a7a923704fd4d4fd238022ba to your computer and use it in GitHub Desktop.

Select an option

Save geekyorion/2c44db81a7a923704fd4d4fd238022ba to your computer and use it in GitHub Desktop.

Revisions

  1. geekyorion created this gist Jan 8, 2023.
    49 changes: 49 additions & 0 deletions userFoundDiscordSnippet.js
    Original 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));