Async flow with generators

suggest change

Generators 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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents