Created
March 20, 2018 20:41
-
-
Save larrybolt/948fb2b51890853cc69acbb69f1c1e63 to your computer and use it in GitHub Desktop.
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
// 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