Skip to content

Instantly share code, notes, and snippets.

@larrybolt
Created March 20, 2018 20:41
Show Gist options
  • Save larrybolt/948fb2b51890853cc69acbb69f1c1e63 to your computer and use it in GitHub Desktop.
Save larrybolt/948fb2b51890853cc69acbb69f1c1e63 to your computer and use it in GitHub Desktop.
// this is our aync function
function query(x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(x * 2)
}, 2000)
});
}
// First, most commonly used way long ago
function getResultOption1(cb) {
query(1).then(res => {
cb(res)
})
}
getResultOption1(result => {
console.log(result)
})
// a bit nicer, we return a promis ourselves
function getResultOption2() {
return new Promise(resolve => {
query(2).then(res => {
resolve(res)
})
})
}
getResultOption2().then(result => {
console.log(result)
})
// modern way using async / await
async function getResultOption3() {
return await query(3)
}
getResultOption3().then(result => {
console.log(result)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment