Created
October 27, 2015 06:11
-
-
Save royriojas/d6924bfa14df32d8e62f to your computer and use it in GitHub Desktop.
async/await example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function isValidEmail(email) { | |
return email.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/); | |
} | |
function getUserByEmail(email) { | |
return new Promise((resolve) => { | |
setTimeout(() => { | |
// keep rejections for exceptions only | |
if (email !== '[email protected]') { | |
return resolve(null); | |
} | |
resolve({ | |
name: 'roy', | |
email: '[email protected]', | |
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: '[email protected]', 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