Created
May 13, 2020 23:57
-
-
Save sangkukbae12/28c79a05d0fca6799f73de29955b7b66 to your computer and use it in GitHub Desktop.
Write simple asynchronous code with JavaScript generators
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
// 1. Use JavaScript (ES6) generators to pause function execution | |
function* createLogger() { | |
console.log('Start') | |
yield | |
console.log('Second block') | |
yield | |
console.log('Third block') | |
yield | |
console.log('End') | |
} | |
const logger = createLogger() | |
logger.next() | |
logger.next() | |
logger.next() | |
logger.next() | |
// 2. Send messages to and from JavaScript (ES6) generators | |
function* createHello() { | |
const word = yield | |
console.log(word) | |
} | |
const hello = createHello() | |
console.log(hello.next()) | |
console.log(hello.next('Max')) | |
// 3. Error handling in JavaScript (ES6) generators | |
function* createHello() { | |
try { | |
const word = yield | |
console.log(`Hello ${word}`) | |
} catch (err) { | |
console.log('ERROR', err) | |
} | |
} | |
const hello = createHello() | |
hello.next() | |
hello.throw('Something went wrong.') | |
// 4. Iterate over JavaScript (ES6) generators | |
function* createCounter() { | |
yield 1 | |
yield 2 | |
yield 3 | |
yield 4 | |
} | |
const counter = createCounter() | |
for (let i of counter) { | |
console.log(i) | |
} | |
// 5. Delegate JavaScript (ES6) generator iteration control | |
function* create3To4Counter() { | |
yield 3 | |
return 4 | |
} | |
function* createCounter() { | |
yield 1 | |
yield 2 | |
const four = yield* create3To4Counter() | |
console.log(four) | |
yield 5 | |
} | |
for (let i of createCounter()) { | |
console.log(i) | |
} | |
// 6. Use JavaScript (ES6) generators with Promises to handle async flows | |
function* createQuoteFetcher() { | |
const response = yield fetch('http://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=json') | |
const quote = yield response.json() | |
return `${quote.quoteText} —${quote.quoteAuthor}` | |
} | |
const coroutine = (gen) => { | |
const generator = gen() | |
const handle = (result) => { | |
if (result.done) return Promise.resolve(result.value) | |
return Promise.resolve(result.value) | |
.then(res => handle(generator.next(res))) | |
} | |
return handle(generator.next()) | |
} | |
const quoteFetcher = coroutine(createQuoteFetcher) | |
quoteFetcher.then(quote => console.log(quote)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment