0

I am trying to find if a user exists in a table given an email and password but I can't get the function to return the right value (currently returns "false"), while the alert inside the function does (alerts "true").

How do I add a callback function to make this work as a synchronous procedure so that the return statement at the end will be true if the user exists?

export const onSignIn = (em, pw) => {

    var authorized = false;
    db.transaction( tx => {
        tx.executeSql(
        `select * from users where email = ? and password = ?;`,
        [em, pw],
        function (transaction, result){
          if (result != null && result.rows != null) {
              for (var i = 0; i < result.rows.length; i++) {
                  var row = result.rows.item(i);
                  if((row.email === em) && (row.password === pw)){
                    authorized = true;
                    alert(authorized)
                  }
              }
          }

        });
    });


    return authorized
}
Nicholas Sizer
  • 3,490
  • 3
  • 26
  • 29
Beltran
  • 11
  • 1
  • 3
  • You don't understand well what async is. Async function does not return a value – CodeLover Feb 16 '18 at 03:13
  • 4
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Ayush Gupta Feb 16 '18 at 03:14
  • What sqlite driver are you using? Doesn't it return a promise? – Bergi Feb 16 '18 at 03:23
  • Sorry if the title was misleading. From what I've read there was a workaround using either async, promises or callback functions. But using callbacks did it. – Beltran Feb 16 '18 at 22:40

1 Answers1

0
export const onSignIn = (em, pw, callback) => {
    db.transaction( tx => {
        tx.executeSql(
        `select * from users where email = ? and password = ?;`,
        [em, pw],
        function (transaction, result){
          if (result != null && result.rows != null) {
              for (var i = 0; i < result.rows.length; i++) {
                  var row = result.rows.item(i);
                  if((row.email === em) && (row.password === pw)){
                    callback(true);
                    alert(authorized);
                    return; // ignore the other results
                  }
              }
          }
          // either no results or results does not contain em,pw
          callback(false);
        });
    });


    return authorized
}

And then you would use the function as such:

onSignIn('user', 'pass', function(success){
  if (success) {
     // code for successful sign in
  } else {
     // code for failed sign in
  }
});
Zach Jones
  • 46
  • 4