Async flow with generators
suggest changeGenerators can pause and then resume. Libraries such as q and co use that to emulate async functions, so the generator can wait for an asynchronous result before continuing:
function someAsyncResult() {
return Promise.resolve('newValue')
}
q.spawn(function * () {
const result = yield someAsyncResult()
console.log(result) // 'newValue'
})
The asynchronous code then reads as if it were synchronous. try/catch covers several asynchronous steps. If the promise is rejected, the error is thrown at the yield and caught by the next catch:
function asyncError() {
return new Promise(function (resolve, reject) {
setTimeout(function () {
reject(new Error('Something went wrong'))
}, 100)
})
}
q.spawn(function * () {
try {
const result = yield asyncError()
} catch (e) {
console.error(e) // Something went wrong
}
})
Using co works the same way, with co(function* () { /* ... */ }) instead of q.spawn.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents