1

我正在从这个精彩的页面学习异步迭代器和生成器,但是当我尝试使用以下“简单”代码时......

  // Note the * after "function"
  async function* asyncRandomNumbers() {
    // This is a web service that returns a random number
    const url = 'https://www.random.org/decimal-fractions/?num=1&dec=10&col=1&format=plain&rnd=new';

    while (true) {
      const response = await fetch(url);
      const text = await response.text();
      yield Number(text);
    }
  }

  async function example() {
    for await (const number of asyncRandomNumbers()) {
      console.log(number);
      if (number > 0.95) break;
    }
  }

  example();

...我的 React 应用程序返回此错误:

Unhandled Rejection (TypeError): Invalid attempt to iterate non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.

错误消息指的是这一行:

async function example() {
^

如果直接在各种浏览器的控制台上使用它不会给我任何问题。

这是为什么?如何在 React 中使用它?

编辑

我正在使用expo来构建我的应用程序。

4

0 回答 0