亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

javascript - Is it okay to use async like this?
PHP中文網(wǎng)
PHP中文網(wǎng) 2017-06-30 09:58:02
0
3
755

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...

PHP中文網(wǎng)
PHP中文網(wǎng)

認(rèn)證高級(jí)PHP講師

reply all(3)
伊謝爾倫

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template