如何在JavaScript中使用异步生成器? [英] How can I use Async Generators in JavaScript?

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

问题描述

我有一个api会返回一个光标来获取更多数据。我嘲笑过这样:

I have an api thats going to return a cursor for fetching more data. I've mocked it out like this:

function fetch(n) {
  return Promise.resolve({
    results: [n],
    next: next < 10 && n + 1,
  })
}

我想要做的是弄清楚我如何使用async / await和生成器来与这个api进行交互。

What I'm trying to do is figure out how I can use async/await along with generators in order to interact with this api.

这基本上是我的原型:

async function* api(url) {
  let result = await fetch(url)
  yield result
  while (result.next) {
    result = await fetch(result.next)
    yield result
  }
}

我的想法是我应该能够创建一个异步生成器并从该生成器获得以迭代光标:

The idea is that I should be able to create an async generator and yield from that generator in order to iterate through the cursor:

async function main() {
  const gen = api(0)
  const zero = await gen.next()
  console.log(zero.result)
  const one = await gen.next()
  console.log(one.result)
  const rest = await Promise.all([...gen])
  console.log(rest.map(r => r.result))
}

考虑到所有因素,我觉得这很甜蜜处理分页数据并能够使用 [... gen] 提取所有数据的方式非常酷。

All things considered, I think this is a pretty sweet way of handling paginated data and being able to pull out all of the data with [...gen] is pretty damn cool.

唯一的问题是,它不起作用!显然你不能使用 async 功能*

Only problem is, it doesn't work! Apprently you can't use async with function*:

❯❯❯ node --version
v7.0.0
❯❯❯ node --harmony --harmony-async-await async-generator.js
/Users/chetcorcos/code/async-generator.js:11
async function* api(url) {
              ^
SyntaxError: Unexpected token *
    at Object.exports.runInThisContext (vm.js:76:16)
    at Module._compile (module.js:545:28)
    at Object.Module._extensions..js (module.js:582:10)
    at Module.load (module.js:490:32)
    at tryModuleLoad (module.js:449:12)
    at Function.Module._load (module.js:441:3)
    at Module.runMain (module.js:607:10)
    at run (bootstrap_node.js:382:7)
    at startup (bootstrap_node.js:137:9)
    at bootstrap_node.js:497:3

但我觉得这应该是可能的。有一个名为 co <​​/a>的热门图书馆,我一直在探索,但我不认为这就是我想要的。

But I really feel like this should be possible. There's a popular library called co that I've been poking around with but I don't think that's what I want.

任何想法如何让异步生成器的概念起作用?

Any ideas how to get this concept of "async generators" to work?

推荐答案

你可以使用Babel插件 transform-async-generator-functions

You can do this using the Babel plugin transform-async-generator-functions.

用法如下:

const g = async i => [ 1, 2, 3 ]
  .map(x => x * 10 ** i);

const f = async function * () {
  for (let i = 0; i < 10; i++) {
    const xs = await g(i);
    for (const x of xs) {
      yield x;
    }
  }
};

const main = async () => {
  for await (const x of f()) {
    console.log(x);
  }
};

main().catch(e => console.error(e));

这是示例回购,显示如何设置项目。

Here is an example repo showing how to setup your project.

重要的部分是 .babelrc 文件:

{
  "presets": [ "env" ], 
  "plugins": [ "transform-async-generator-functions" ]
 }

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

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