Last active
September 18, 2016 19:33
-
-
Save softwarespot/2207c6960f32fc7708c5aa33ee774cee to your computer and use it in GitHub Desktop.
async/await Examples
This file contains hidden or 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
// Idea 1: https://medium.com/@bluepnume/learn-about-promises-before-you-start-using-async-await-eb148164a9c8#.s6914ps6a | |
// Use: https://babeljs.io/repl/ to transpile as ES5 | |
async function asyncDemo() { | |
try { | |
const res = await getJSON() // Promise.all([getJSON(), getJSON()]) for concurrent requests | |
console.log(res.value) | |
} catch (err) { | |
console.log(err) | |
} | |
console.log('The following output is displayed afterwards') | |
} | |
function getJSON() { | |
return new Promise((resolve, reject) => { | |
const value = Math.ceil(Math.random() * 5000) | |
setTimeout(() => { | |
console.log('Random Value: ', value) | |
if (value % 2 === 0) { | |
resolve({ value }) | |
} else { | |
reject(new Error('An error occurred with the following async request')) | |
} | |
}, 2000) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment