Skip to content

Instantly share code, notes, and snippets.

@royriojas
Created October 27, 2015 06:11
Show Gist options
  • Save royriojas/d6924bfa14df32d8e62f to your computer and use it in GitHub Desktop.
Save royriojas/d6924bfa14df32d8e62f to your computer and use it in GitHub Desktop.
async/await example
function isValidEmail(email) {
return email.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/);
}
function getUserByEmail(email) {
return new Promise((resolve) => {
setTimeout(() => {
// keep rejections for exceptions only
if (email !== 'roy@someemail.com') {
return resolve(null);
}
resolve({
name: 'roy',
email: 'roy@someemail.com',
password: 'abc123$'
});
}, 1000);
});
}
function compare(p1, p2) {
return new Promise((resolve) => {
setTimeout(() => {
// keep reject for failures
resolve(p1 === p2);
}, 1000);
});
}
async function getByEmailAndPassword({ email, password }) {
const isValid = await isValidEmail(email);
if (!isValid) {
return {
token: 'INVALID_EMAIL'
};
}
const user = await getUserByEmail(email);
if (!user) {
return {
token: 'EMAIL_AND_PASSWORD_MISMATCH'
};
}
const isCorrect = await compare(password, user.password);
if (!isCorrect) {
return { token: 'EMAIL_AND_PASSWORD_MISMATCH' };
}
return user;
}
getByEmailAndPassword({ email: 'roy@someemail.com', password: 'abc123$' }).then((result) => {
console.log('result', result);
}, (err) => console.error(err));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment