Kat*_*rax 4 asynchronous node.js express pg-promise
我想使用pg-promise.
我使用以下查询:
this.db.one('SELECT EXISTS(SELECT 1 FROM users WHERE username = $1)', username);
Run Code Online (Sandbox Code Playgroud)
我试图将此查询封装在一个函数中,如果用户名存在,则该函数仅返回 true,否则返回 false。
就像是:
existsUsername(username){
this.db.one('SELECT EXISTS(SELECT 1 FROM users WHERE username = $1)', username)
.then(data => {
if(data.exists == true){
return true;
} else {
return false;
}
});
}
Run Code Online (Sandbox Code Playgroud)
我可以像这样简单地使用:
if(db.users.existsUsername(username)){
// this username is already taken
}
Run Code Online (Sandbox Code Playgroud)
但是,在查询完成之前评估 if 条件,从而导致未定义的变量。
返回查询结果的正确方法是什么?
编辑:外部调用者执行多个异步检查并返回用户是否有效:
function signUp(username, email, ...){
// perform username existence check existsUser(username)
// perform email existence check existsEmail(username)
// ...
// if everything OK, put user in DB
}
Run Code Online (Sandbox Code Playgroud)
Simplest way of doing it:
existsUsername(username) {
return this.db.oneOrNone('SELECT * FROM users WHERE username = $1 LIMIT 1', username, a => !!a);
}
Run Code Online (Sandbox Code Playgroud)
And then use it:
db.users.existsUsername(username)
.then(exists => {
// exists - boolean
})
.catch(error => {
});
Run Code Online (Sandbox Code Playgroud)
You cannot do things like if(db.users.existsUsername(username)), that's mixing up synchronous code with asynchronous. But you can do if(await db.users.existsUsername(username)), if ES7 syntax is available to you.
And if you have three independent functions like that (checkUserName, checkEmail, checkWhateverElse), and want to execute them all, here's the best way to do it:
db.task(t => {
return t.batch([checkUserName(t), checkEmail(t), checkWhateverElse(t)]);
})
.then(data => {
// data = result of the batch operation;
})
.catch(error => {
// error
});
Run Code Online (Sandbox Code Playgroud)
The same with ES7 syntax:
db.task(async t => {
const a = await checkUserName(t);
const b = await checkEmail(t);
const c = await checkWhateverElse(t);
return {a, b, c};
})
.then(data => {
// data = {a, b, c} object;
})
.catch(error => {
// error
});
Run Code Online (Sandbox Code Playgroud)
Note: Each of those functions is expected to execute queries against t - task context, in order to share the connection.
| 归档时间: |
|
| 查看次数: |
3177 次 |
| 最近记录: |