码迷,mamicode.com
首页 > 其他好文 > 详细

async await

时间:2017-09-13 00:29:54      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:webstorm   mongodb   find   closure   node   options   href   count   targe   

async await可以说是避免回调地狱的终极解决方案,也能解决Promise不能良好解决的分支问题,保持逻辑清晰,加上Webstorm支持的Google Closure Compiler注解,代码简直爽的不要不要的。贴一段:

/** @typedef {{username:string, password:string}} UserData */

/**
 * Create a new account. Doesn't check username and password.
 *
 * @param {UserData} opt
 * @return {Promise<?User>}
 */
static async createNewAccount(opt) {
    const options = {
        username: opt.username,
        password: opt.password
    };
    const collection = await mongodb.collection(COLLECTION);
    const doc = await collection.findOne({username: options.username});
    if (doc != null) {
        return null;
    }
    const userData = {
        username: options.username,
        password: UserDao._saltAndHash(options.password)
    };
    const user = new User(userData);
    const result = await collection.insertOne(user.toObject(), {safe: true});
    user.id = result.insertedId;
    return user;
}

在Node刚支持ES6的时候,一些维护很积极的库就把代码用Promise重写了,现在估计又要用async await重写了

async await

标签:webstorm   mongodb   find   closure   node   options   href   count   targe   

原文地址:http://www.cnblogs.com/nurdun/p/7512838.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!