Created
September 18, 2016 19:37
-
-
Save softwarespot/e9ef9162b096f23c4b55ee953f9fa901 to your computer and use it in GitHub Desktop.
yield/generator/bluebird
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://www.promisejs.org/generators/ | |
// Idea 2: http://bluebirdjs.com/docs/api/promise.coroutine.html | |
const asyncDemo = Promise.coroutine(function* () { | |
try { | |
const res = yield getJSON() | |
console.log(res.value) | |
} catch (err) { | |
console.log(err) | |
} | |
}) | |
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