我想知道生成器完成后是否可以将连续生成的值作为数组返回。这是我到目前为止所尝试过的,我在生成器末尾添加了一个 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/