我试图找到一个用户是否存在于给定电子邮件和密码的表中,但是我无法使该函数返回正确的值(当前返回“false”),而函数内部的警报确实存在(警报) “真正”)。
如何添加回调函数以使其作为同步过程工作,以便如果用户存在,则结尾的return语句为true?
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
}
答案 0 :(得分: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
}
然后你会使用这个函数:
onSignIn('user', 'pass', function(success){
if (success) {
// code for successful sign in
} else {
// code for failed sign in
}
});