编写函数发生器管道示例的实际使用案例。
[当我们使用JavaScript编写同步函数时,我们通常希望其中的代码将一直执行到到达return语句,错误或功能块的结尾:
function shout(text) {
const shouty = text.toUpperCase();
return `${shouty}!`;
}
shout("hello, world"); // "HELLO, WORLD!"
使用Generator函数,我们使用yield关键字更改了期望值。当我们在函数中遇到yield时,表示要暂停执行,允许我们在函数执行完成之前从函数中获取值:
function* shoutGenerator(text) {
const shouty = text.toUpperCase();
yield shouty;
return `${shouty}!`;
}
const shout = shoutGenerator("hello, world");
shout.next(); // { done: false, value: "HELLO, WORLD" }
shout.next(); // { done: true, value: "HELLO, WORLD!" }
在这个公认的人为例子中,我们可以在到达return语句之前从函数中提取高喊的值。让我们看看如何将值传递到暂停的函数中:
function* shoutGenerator(text) {
const shouty = text.toUpperCase();
const volume = yield shouty;
return shouty + new Array(volume).fill("!").join("");
}
const shoutWithVolume = shoutGenerator(“ hi”);
shoutWithVolume.next(); // {已完成:false,值:“ HI”}shoutWithVolume.next(11); // {done:true,值:“ HI !!!!!!!!!!!” }
将值传递给Iterator协议公开的next()方法使我们可以在恢复执行时使用它。