javascript - 生成器完成后,以数组形式返回连续产生的值

标签 javascript ecmascript-6 generator

我想知道生成器完成后是否可以将连续生成的值作为数组返回。这是我到目前为止所尝试过的,我在生成器末尾添加了一个 return 语句并尝试解构输出:

function ajax(url) {
  fetch(url).then(data => data.json()).then(data => dataGen.next(data))
}

function* steps() {
  const beers = yield ajax('http://api.react.beer/v2/search?q=hops&type=beer');

  const wes = yield ajax('https://api.github.com/users/wesbos');

  const fatJoe = yield ajax('https://api.discogs.com/artists/51988');

  return [beers, wes, fatJoe]
}

const dataGen = steps();
const [beers, wes, fatJoe] = dataGen.next(); // kick it off

但是,没有返回任何值:

Uncaught ReferenceError: beers is not defined
Uncaught ReferenceError: wes is not defined
Uncaught ReferenceError: fatJoe is not defined

最佳答案

如果正确解释问题,您可以使用yield*,将steps()调用传递给Promise.all()。然后()

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Generators</title>
</head>
<body>
<script>

  function ajax(url) {
    return fetch(url).then(data => data.json()).then(data => data)
  }

  function* steps() {
    yield* [
             ajax('data:application/json,[1]')
             , ajax('data:application/json,[2]')
             , ajax('data:application/json,[3]')
           ];
  }

  // kick it off
  Promise.all(steps())
  .then(([beers, wes, fatJoe]) => 
    console.log(beers, wes, fatJoe)
  )
</script>
</body>
</html>

或者没有生成器函数的Promise.all()

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Generators</title>
</head>
<body>
<script>

  function ajax(url) {
    return fetch(url).then(data => data.json()).then(data => data)
  }

  function steps() {
    return [
             ajax('data:application/json,[1]')
             , ajax('data:application/json,[2]')
             , ajax('data:application/json,[3]')
           ];
  }

  // kick it off
  Promise.all(steps())
  .then(([beers, wes, fatJoe]) => 
    console.log(beers, wes, fatJoe)
  )
</script>
</body>
</html>

关于javascript - 生成器完成后,以数组形式返回连续产生的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44346970/

相关文章:

c++ - 如何使用当前时间为随机数生成器播种、显示标题并将随机出生日期分配给 X 数量的人 (C++)

javascript - owl carousel 2 在部分可见时开始自动播放

javascript - 展开浏览器后不会显示响应式导航菜单

javascript - 如何根据单击的复选框显示/隐藏特定图像(单击 cbox3 应打开 tinypic3)

Javascript (ES6) 日期到字符串格式

javascript - 如何在 React JS 中创建一个类和另一个类扩展该类

javascript - 在原型(prototype)内部定义函数(如 toString 函数)

ide - 不接受Webstorm生成器功能

javascript - 进行嵌套/递归计算时如何运行事件循环?

javascript - 高亮显示DIV中的文本时,如何获取DIV中Span的值? (JavaScript)