Skip to content

Instantly share code, notes, and snippets.

@benjamingr
Last active August 29, 2015 14:23
Show Gist options
  • Save benjamingr/d08cfe94d3f0db1f954d to your computer and use it in GitHub Desktop.
Save benjamingr/d08cfe94d3f0db1f954d to your computer and use it in GitHub Desktop.
function createUser(username, callback) {
var connection = DatabaseClient.connect();
var users = connection.call('collection', 'users');
var query = users.call('query', {username: username});
return query.then(function(existing){
if(existing) throw new Error("User already exists: " + username);
else return users.call('create', {username: username});
}).fin(function(connection){ return connection.call('close'); });
}
async function createUser(username, callback) {
var connection = await DatabaseClient.connect();
try{
var users = await connection.collection('users');
var query = await users.query({username: username});
if(query){
throw new Error("User already exists: " + username);
} else {
return await users.create({username: username});
}
} finally {
connection.close();
}
}
function createUser(username, callback) {
return DatabaseClient.connect().then(function(connection) {
return connection.collection('users').then(function(users) {
return users.query({username: username}).then(function(existing) {
if (existing) {
callback("User already exists: " + username);
} else {
return users.create({username: username}).then(function (user) {
callback(null, user);
});
}
});
}).fin(connection.close);
}).catch(callback);
}
@abrkn
Copy link

abrkn commented Jun 25, 2015

async function createUser(username, callback) {
    const connection = await DatabaseClient.connect();
    try {
        const users = await connection.collection('users');
        const query = await users.query({ username });
        if (query) { throw new Error(`User already exists: ${username}`); }
        return await users.create({ username });
    } finally {
        connection.close();
    }
}

@benjamingr
Copy link
Author

@sukima nice, that also works

@abrkn nice, I really should use const more.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment