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;
// 查找當(dāng)前用戶名是否已經(jīng)注冊(cè)(返回值為數(shù)組,沒有結(jié)果則為空數(shù)組,長(zhǎng)度為0)
let userIsRegisted = await user.findByName(username);
// 因?yàn)橛脩裘奈ㄒ恍?可以使用==1或者!=0兩種方式判斷
if(userIsRegisted.length!=0){
res.send('當(dāng)前用戶已注冊(cè)');
return;
}
// 密碼加密
let hashPassword = crypto.createHash('sha1').update(password).digest('hex');
let obj = {
username:username,
password:hashPassword
}
// 添加新用戶
await user.create(obj);
// 設(shè)置session
req.session.username=username;
req.session.loged = true;
res.send('注冊(cè)成功');
})();
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...
認(rèn)證高級(jí)PHP講師
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.
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
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.