Javascript Async Generator

2019-02-19 19:10发布

Is it possible to write an asynchronous generator like the following:

function gen() {
  return async function * () {
    yield await ...
    yield await ...
    yield await ...
  }()
}

So one can use it like this, for example:

for (let val of await gen()) {
  ...
}

I can't really work out the semantics of this construction, how are async generators used in loops?

1条回答
甜甜的少女心
2楼-- · 2019-02-19 19:37

Until the async iteration proposal is complete, you could take a page from the Redux-saga book (like Cory Danielson mentioned) and have an adapter function that does all the async/await stuff.

const later = async (delay, value) => {
    return new Promise(resolve => {
        setTimeout(() => resolve(value), delay);
    });
};

function* rangePromise() {
    for (let i = 2; i < 10; i++) {
        let nextValue = yield later(100, i);
        yield nextValue;
    }
}

const forEachAsyncAdapter = async (iterator, ...callbacks) => {
    try {
        let next = iterator.next();
        while (!next.done) {
            while (!next.done && next.value && next.value.then) {
                next = iterator.next(await next.value);
            }
            if (!next.done) {
                await callbacks.reduce(
                    async (nextValue, callback) => {
                        nextValue = await callback(await nextValue);
                        return nextValue;
                    },
                    Promise.resolve(next.value)
                );
                next = iterator.next();
            }
        }
    } finally {
        if (typeof iterator.return === 'function') {
            iterator.return();
        }
    }
};


forEachAsyncAdapter(
    rangePromise(),
    async i => { console.log(i); return Array(i).join('a'); },
    async s => { console.log(s); return s.toUpperCase(); },
    async s => { console.log(s); }
);

查看更多
登录 后发表回答