I recently read some articles and started to use async to handle asynchronous code. It is much easier to use than the previous asynchronous callbacks. However, I found that there seems to be a problem with my writing method. I posted it and everyone can help me correct it....
(async function(){
let username = req.body.username;
let password = req.body.password;
// 查找当前用户名是否已经注册(返回值为数组,没有结果则为空数组,长度为0)
let userIsRegisted = await user.findByName(username);
// 因为用户名的唯一性,可以使用==1或者!=0两种方式判断
if(userIsRegisted.length!=0){
res.send('当前用户已注册');
return;
}
// 密码加密
let hashPassword = crypto.createHash('sha1').update(password).digest('hex');
let obj = {
username:username,
password:hashPassword
}
// 添加新用户
await user.create(obj);
// 设置session
req.session.username=username;
req.session.loged = true;
res.send('注册成功');
})();
Regardless of the logic of writing, this is the calling method, right? It always feels weird that I need to write an immediate execution function...
伊谢尔伦2017-06-30 10:00:02
If the anonymous function is not declared as async, this way of writing will feel strange. Since await is used in this anonymous function to call another function, it must be declared as async, otherwise a compilation error will be reported. It can be executed immediately as written by the original poster. However, it is more recommended to declare a function name for the anonymous function and call the function asynchronously.
迷茫2017-06-30 10:00:02
Use try catch more often. Also, I’m not sure why you include an immediate execution function here. Define a name for the async function. You can customize the call later
怪我咯2017-06-30 10:00:02
Generally, it’s no problem to use it this way. When the async function is called with await, it returns immediately from the main function. When the async function ends, it continues to execute the main function.
If await is not used, the main function will be executed. At the same time, the async function will be executed asynchronously.