Javascript异步生成器 [英] Javascript Async Generator

查看:73
本文介绍了Javascript异步生成器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以编写如下的异步生成器:

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?

推荐答案

在异步迭代提议完成之前,您可以从Redux-saga书中获取一个页面(如Cory Danielson所提到的),并有一个适配器函数可以执行所有异步/等待事务。

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); }
);

这篇关于Javascript异步生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆