Created
June 21, 2018 06:13
-
-
Save gsrai/babfc7b28fe82266b935559999dbcd1e to your computer and use it in GitHub Desktop.
Example of Async/Await vs Promises vs Promise.all
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
// Async Await is syntactic sugar over promises | |
// They are not a complete replacement as you still need to construct Promise objects | |
// and methods like Promise.all([]) can only be done with promises | |
const myFetch1 = () => { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
if (Math.random() > 0.05) { // change this to trigger the catch blocks | |
resolve('foo') | |
} else { | |
reject('Something went wrong') | |
} | |
}, 2000) | |
}) | |
} | |
const myFetch2 = () => { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
if (Math.random() > 0.15) { | |
resolve('bar') | |
} else { | |
reject('Something went wrong') | |
} | |
}, 3000) | |
}) | |
} | |
function getPromiseFoobar(cb) { | |
const errCB = (err) => console.error(`something went wrong in getPromiseFoobar: ${err}`) | |
myFetch1().then(val1 => { | |
myFetch2().then(val2 => { | |
cb(val1 + val2) | |
}).catch(errCB) | |
}).catch(errCB) | |
} | |
function getPromiseAllFoobar(cb) { | |
Promise.all([myFetch1(), myFetch2()]) | |
.then(([a, b]) => cb(a + b)) | |
.catch((err) => console.error(`something went wrong in getPromiseAllFoobar: ${err}`)) | |
} | |
async function getFoobar(cb) { | |
try { | |
const a = await myFetch1() | |
const b = await myFetch2() | |
cb(a + b) | |
} catch(err) { | |
console.error(`something went wrong in getFoobar: ${err}`) | |
} | |
} | |
function main() { | |
getFoobar(foobar => console.log('async await: ', foobar)) | |
getPromiseFoobar(foobar => console.log('promise: ', foobar)) | |
getPromiseAllFoobar(foobar => console.log('promise all: ', foobar)) | |
} | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment