async await

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重写了

posted @ 2017-09-12 23:29  nurdun  阅读(216)  评论(0编辑  收藏  举报